forked from openiddict/openiddict-core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOpenIddictServerBuilder.cs
More file actions
2471 lines (2135 loc) · 113 KB
/
OpenIddictServerBuilder.cs
File metadata and controls
2471 lines (2135 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Server;
namespace Microsoft.Extensions.DependencyInjection;
/// <summary>
/// Exposes the necessary methods required to configure the OpenIddict server services.
/// </summary>
public sealed class OpenIddictServerBuilder
{
/// <summary>
/// Initializes a new instance of <see cref="OpenIddictServerBuilder"/>.
/// </summary>
/// <param name="services">The services collection.</param>
public OpenIddictServerBuilder(IServiceCollection services)
=> Services = services ?? throw new ArgumentNullException(nameof(services));
/// <summary>
/// Gets the services collection.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public IServiceCollection Services { get; }
/// <summary>
/// Registers an event handler using the specified configuration delegate.
/// </summary>
/// <typeparam name="TContext">The event context type.</typeparam>
/// <param name="configuration">The configuration delegate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public OpenIddictServerBuilder AddEventHandler<TContext>(
Action<OpenIddictServerHandlerDescriptor.Builder<TContext>> configuration)
where TContext : BaseContext
{
ArgumentNullException.ThrowIfNull(configuration);
// Note: handlers registered using this API are assumed to be custom handlers by default.
var builder = OpenIddictServerHandlerDescriptor.CreateBuilder<TContext>()
.SetType(OpenIddictServerHandlerType.Custom);
configuration(builder);
return AddEventHandler(builder.Build());
}
/// <summary>
/// Registers an event handler using the specified descriptor.
/// </summary>
/// <param name="descriptor">The handler descriptor.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public OpenIddictServerBuilder AddEventHandler(OpenIddictServerHandlerDescriptor descriptor)
{
ArgumentNullException.ThrowIfNull(descriptor);
// Register the handler in the services collection.
Services.Add(descriptor.ServiceDescriptor);
return Configure(options => options.Handlers.Add(descriptor));
}
/// <summary>
/// Removes the event handler that matches the specified descriptor.
/// </summary>
/// <param name="descriptor">The descriptor corresponding to the handler to remove.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public OpenIddictServerBuilder RemoveEventHandler(OpenIddictServerHandlerDescriptor descriptor)
{
ArgumentNullException.ThrowIfNull(descriptor);
Services.RemoveAll(descriptor.ServiceDescriptor.ServiceType);
Services.PostConfigure<OpenIddictServerOptions>(options =>
{
for (var index = options.Handlers.Count - 1; index >= 0; index--)
{
if (options.Handlers[index].ServiceDescriptor.ServiceType == descriptor.ServiceDescriptor.ServiceType)
{
options.Handlers.RemoveAt(index);
}
}
});
return this;
}
/// <summary>
/// Amends the default OpenIddict server configuration.
/// </summary>
/// <param name="configuration">The delegate used to configure the OpenIddict options.</param>
/// <remarks>This extension can be safely called multiple times.</remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder Configure(Action<OpenIddictServerOptions> configuration)
{
ArgumentNullException.ThrowIfNull(configuration);
Services.Configure(configuration);
return this;
}
/// <summary>
/// Makes client identification optional so that token, introspection and revocation
/// requests that don't specify a client_id are not automatically rejected.
/// </summary>
/// <remarks>
/// Enabling this option is NOT recommended and should only be used for
/// backward compatibility with legacy authorization server deployments.
/// </remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AcceptAnonymousClients()
=> Configure(options => options.AcceptAnonymousClients = true);
/// <summary>
/// Registers encryption credentials.
/// </summary>
/// <param name="credentials">The encrypting credentials.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCredentials(EncryptingCredentials credentials)
{
ArgumentNullException.ThrowIfNull(credentials);
return Configure(options => options.EncryptionCredentials.Add(credentials));
}
/// <summary>
/// Registers an encryption key.
/// </summary>
/// <param name="key">The security key.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionKey(SecurityKey key)
{
ArgumentNullException.ThrowIfNull(key);
// If the encryption key is an asymmetric security key, ensure it has a private key.
if (key is AsymmetricSecurityKey { PrivateKeyStatus: PrivateKeyStatus.DoesNotExist })
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0055));
}
if (key.IsSupportedAlgorithm(SecurityAlgorithms.Aes256KW))
{
if (key.KeySize != 256)
{
throw new InvalidOperationException(SR.FormatID0283(256, key.KeySize));
}
return AddEncryptionCredentials(new EncryptingCredentials(key,
SecurityAlgorithms.Aes256KW, SecurityAlgorithms.Aes256CbcHmacSha512));
}
if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaOAEP))
{
return AddEncryptionCredentials(new EncryptingCredentials(key,
SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512));
}
throw new InvalidOperationException(SR.GetResourceString(SR.ID0056));
}
/// <summary>
/// Registers multiple encryption keys.
/// </summary>
/// <param name="keys">The security keys.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionKeys(IEnumerable<SecurityKey> keys)
{
ArgumentNullException.ThrowIfNull(keys);
return keys.Aggregate(this, static (builder, key) => builder.AddEncryptionKey(key));
}
/// <summary>
/// Registers (and generates if necessary) a user-specific development encryption certificate.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddDevelopmentEncryptionCertificate()
=> AddDevelopmentEncryptionCertificate(new X500DistinguishedName("CN=OpenIddict Server Encryption Certificate"));
/// <summary>
/// Registers (and generates if necessary) a user-specific development encryption certificate.
/// </summary>
/// <param name="subject">The subject name associated with the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddDevelopmentEncryptionCertificate(X500DistinguishedName subject)
{
ArgumentNullException.ThrowIfNull(subject);
Services.AddOptions<OpenIddictServerOptions>().Configure<IServiceProvider>((options, provider) =>
{
// Important: the time provider might not be set yet when this configuration delegate is called.
// In that case, resolve the provider from the service provider or use the default time provider.
var now = (options.TimeProvider ?? provider.GetService<TimeProvider>() ?? TimeProvider.System).GetUtcNow();
using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
// Try to retrieve the existing development certificates from the specified store.
// If no valid existing certificate was found, create a new encryption certificate.
var certificates = store.Certificates
.Find(X509FindType.FindBySubjectDistinguishedName, subject.Name, validOnly: false)
.Cast<X509Certificate2>()
.ToList();
if (!certificates.Exists(certificate => certificate.NotBefore < now.LocalDateTime && certificate.NotAfter > now.LocalDateTime))
{
#if SUPPORTS_CERTIFICATE_GENERATION
using var algorithm = OpenIddictHelpers.CreateRsaKey(size: 4096);
var request = new CertificateRequest(subject, algorithm, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyEncipherment, critical: true));
var certificate = request.CreateSelfSigned(now, now.AddYears(2));
// Note: setting the friendly name is not supported on Unix machines (including Linux and macOS).
// To ensure an exception is not thrown by the property setter, an OS runtime check is used here.
if (OperatingSystem.IsWindows())
{
certificate.FriendlyName = "OpenIddict Server Development Encryption Certificate";
}
// Note: CertificateRequest.CreateSelfSigned() doesn't mark the key set associated with the certificate
// as "persisted", which eventually prevents X509Store.Add() from correctly storing the private key.
// To work around this issue, the certificate payload is manually exported and imported back
// into a new X509Certificate2 instance specifying the X509KeyStorageFlags.PersistKeySet flag.
var data = certificate.Export(X509ContentType.Pfx, string.Empty);
try
{
var flags = X509KeyStorageFlags.PersistKeySet;
// Note: macOS requires marking the certificate private key as exportable.
// If this flag is not set, a CryptographicException is thrown at runtime.
if (OperatingSystem.IsMacOS())
{
flags |= X509KeyStorageFlags.Exportable;
}
#if SUPPORTS_CERTIFICATE_LOADER
certificate = X509CertificateLoader.LoadPkcs12(data, string.Empty, flags);
#else
certificate = new X509Certificate2(data, string.Empty, flags);
#endif
certificates.Insert(0, certificate);
}
finally
{
Array.Clear(data, 0, data.Length);
}
store.Add(certificate);
#else
throw new PlatformNotSupportedException(SR.GetResourceString(SR.ID0264));
#endif
}
options.EncryptionCredentials.AddRange(
from certificate in certificates
let key = new X509SecurityKey(certificate)
select new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP,
SecurityAlgorithms.Aes256CbcHmacSha512));
});
return this;
}
/// <summary>
/// Registers a new ephemeral encryption key. Ephemeral encryption keys are automatically
/// discarded when the application shuts down and payloads encrypted using this key are
/// automatically invalidated. This method should only be used during development.
/// On production, using a X.509 certificate stored in the machine store is recommended.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEphemeralEncryptionKey()
=> AddEphemeralEncryptionKey(SecurityAlgorithms.RsaOAEP);
/// <summary>
/// Registers a new ephemeral encryption key. Ephemeral encryption keys are automatically
/// discarded when the application shuts down and payloads encrypted using this key are
/// automatically invalidated. This method should only be used during development.
/// On production, using a X.509 certificate stored in the machine store is recommended.
/// </summary>
/// <param name="algorithm">The algorithm associated with the encryption key.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEphemeralEncryptionKey(string algorithm)
{
ArgumentException.ThrowIfNullOrEmpty(algorithm);
return algorithm switch
{
SecurityAlgorithms.Aes256KW
=> AddEncryptionCredentials(new EncryptingCredentials(
new SymmetricSecurityKey(OpenIddictHelpers.CreateRandomArray(size: 256)),
algorithm, SecurityAlgorithms.Aes256CbcHmacSha512)),
SecurityAlgorithms.RsaOAEP or
SecurityAlgorithms.RsaOaepKeyWrap
=> AddEncryptionCredentials(new EncryptingCredentials(
new RsaSecurityKey(OpenIddictHelpers.CreateRsaKey(size: 4096)),
algorithm, SecurityAlgorithms.Aes256CbcHmacSha512)),
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0058))
};
}
/// <summary>
/// Registers an encryption certificate.
/// </summary>
/// <param name="certificate">The encryption certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(X509Certificate2 certificate)
{
ArgumentNullException.ThrowIfNull(certificate);
// If the certificate is a X.509v3 certificate that specifies at least one
// key usage, ensure that the certificate key can be used for key encryption.
if (certificate.Version is >= 3)
{
var extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
if (extensions.Count is not 0 && !extensions.Exists(static extension =>
extension.KeyUsages.HasFlag(X509KeyUsageFlags.KeyEncipherment)))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0060));
}
}
if (!certificate.HasPrivateKey)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0061));
}
return AddEncryptionKey(new X509SecurityKey(certificate));
}
/// <summary>
/// Registers an encryption certificate retrieved from an embedded resource.
/// </summary>
/// <param name="assembly">The assembly containing the certificate.</param>
/// <param name="resource">The name of the embedded resource.</param>
/// <param name="password">The password used to open the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(Assembly assembly, string resource, string? password)
#if SUPPORTS_EPHEMERAL_KEY_SETS
// Note: ephemeral key sets are currently not supported on macOS.
=> AddEncryptionCertificate(assembly, resource, password, OperatingSystem.IsMacOS() ?
X509KeyStorageFlags.MachineKeySet :
X509KeyStorageFlags.EphemeralKeySet);
#else
=> AddEncryptionCertificate(assembly, resource, password, X509KeyStorageFlags.MachineKeySet);
#endif
/// <summary>
/// Registers an encryption certificate retrieved from an embedded resource.
/// </summary>
/// <param name="assembly">The assembly containing the certificate.</param>
/// <param name="resource">The name of the embedded resource.</param>
/// <param name="password">The password used to open the certificate.</param>
/// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(
Assembly assembly, string resource,
string? password, X509KeyStorageFlags flags)
{
ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return AddEncryptionCertificate(stream, password, flags);
}
/// <summary>
/// Registers an encryption certificate extracted from a stream.
/// </summary>
/// <param name="stream">The stream containing the certificate.</param>
/// <param name="password">The password used to open the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(Stream stream, string? password)
#if SUPPORTS_EPHEMERAL_KEY_SETS
// Note: ephemeral key sets are currently not supported on macOS.
=> AddEncryptionCertificate(stream, password, OperatingSystem.IsMacOS() ?
X509KeyStorageFlags.MachineKeySet :
X509KeyStorageFlags.EphemeralKeySet);
#else
=> AddEncryptionCertificate(stream, password, X509KeyStorageFlags.MachineKeySet);
#endif
/// <summary>
/// Registers an encryption certificate extracted from a stream.
/// </summary>
/// <param name="stream">The stream containing the certificate.</param>
/// <param name="password">The password used to open the certificate.</param>
/// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(Stream stream, string? password, X509KeyStorageFlags flags)
{
ArgumentNullException.ThrowIfNull(stream);
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
#if SUPPORTS_CERTIFICATE_LOADER
var certificate = X509Certificate2.GetCertContentType(buffer.ToArray()) switch
{
X509ContentType.Pkcs12 => X509CertificateLoader.LoadPkcs12(buffer.ToArray(), password, flags),
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0454))
};
#else
var certificate = new X509Certificate2(buffer.ToArray(), password, flags);
#endif
return AddEncryptionCertificate(certificate);
}
/// <summary>
/// Registers an encryption certificate retrieved from the X.509 user or machine store.
/// </summary>
/// <param name="thumbprint">The thumbprint of the certificate used to identify it in the X.509 store.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(string thumbprint)
{
ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return AddEncryptionCertificate(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ??
GetCertificate(StoreLocation.LocalMachine, thumbprint) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{
using var store = new X509Store(StoreName.My, location);
store.Open(OpenFlags.ReadOnly);
return store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.Cast<X509Certificate2>()
.SingleOrDefault();
}
}
/// <summary>
/// Registers an encryption certificate retrieved from the specified X.509 store.
/// </summary>
/// <param name="thumbprint">The thumbprint of the certificate used to identify it in the X.509 store.</param>
/// <param name="name">The name of the X.509 store.</param>
/// <param name="location">The location of the X.509 store.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificate(string thumbprint, StoreName name, StoreLocation location)
{
ArgumentException.ThrowIfNullOrEmpty(thumbprint);
using var store = new X509Store(name, location);
store.Open(OpenFlags.ReadOnly);
return AddEncryptionCertificate(
store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.Cast<X509Certificate2>()
.SingleOrDefault() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
}
/// <summary>
/// Registers multiple encryption certificates.
/// </summary>
/// <param name="certificates">The encryption certificates.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEncryptionCertificates(IEnumerable<X509Certificate2> certificates)
{
ArgumentNullException.ThrowIfNull(certificates);
return certificates.Aggregate(this, static (builder, certificate) => builder.AddEncryptionCertificate(certificate));
}
/// <summary>
/// Registers signing credentials.
/// </summary>
/// <param name="credentials">The signing credentials.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCredentials(SigningCredentials credentials)
{
ArgumentNullException.ThrowIfNull(credentials);
return Configure(options => options.SigningCredentials.Add(credentials));
}
/// <summary>
/// Registers a signing key.
/// </summary>
/// <param name="key">The security key.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningKey(SecurityKey key)
{
ArgumentNullException.ThrowIfNull(key);
// If the signing key is an asymmetric security key, ensure it has a private key.
if (key is AsymmetricSecurityKey { PrivateKeyStatus: PrivateKeyStatus.DoesNotExist })
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0067));
}
if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha256))
{
return AddSigningCredentials(new SigningCredentials(key, SecurityAlgorithms.RsaSha256));
}
if (key.IsSupportedAlgorithm(SecurityAlgorithms.HmacSha256))
{
return AddSigningCredentials(new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
}
#if SUPPORTS_ECDSA
// Note: ECDSA algorithms are bound to specific curves and must be treated separately.
if (key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha256))
{
return AddSigningCredentials(new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256));
}
if (key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha384))
{
return AddSigningCredentials(new SigningCredentials(key, SecurityAlgorithms.EcdsaSha384));
}
if (key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha512))
{
return AddSigningCredentials(new SigningCredentials(key, SecurityAlgorithms.EcdsaSha512));
}
#else
if (key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha256) ||
key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha384) ||
key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha512))
{
throw new PlatformNotSupportedException(SR.GetResourceString(SR.ID0069));
}
#endif
throw new InvalidOperationException(SR.GetResourceString(SR.ID0068));
}
/// <summary>
/// Registers multiple signing keys.
/// </summary>
/// <param name="keys">The signing keys.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningKeys(IEnumerable<SecurityKey> keys)
{
ArgumentNullException.ThrowIfNull(keys);
return keys.Aggregate(this, static (builder, key) => builder.AddSigningKey(key));
}
/// <summary>
/// Registers (and generates if necessary) a user-specific development signing certificate.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddDevelopmentSigningCertificate()
=> AddDevelopmentSigningCertificate(new X500DistinguishedName("CN=OpenIddict Server Signing Certificate"));
/// <summary>
/// Registers (and generates if necessary) a user-specific development signing certificate.
/// </summary>
/// <param name="subject">The subject name associated with the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddDevelopmentSigningCertificate(X500DistinguishedName subject)
{
ArgumentNullException.ThrowIfNull(subject);
Services.AddOptions<OpenIddictServerOptions>().Configure<IServiceProvider>((options, provider) =>
{
// Important: the time provider might not be set yet when this configuration delegate is called.
// In that case, resolve the provider from the service provider or use the default time provider.
var now = (options.TimeProvider ?? provider.GetService<TimeProvider>() ?? TimeProvider.System).GetUtcNow();
using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
// Try to retrieve the existing development certificates from the specified store.
// If no valid existing certificate was found, create a new signing certificate.
var certificates = store.Certificates
.Find(X509FindType.FindBySubjectDistinguishedName, subject.Name, validOnly: false)
.Cast<X509Certificate2>()
.ToList();
if (!certificates.Exists(certificate => certificate.NotBefore < now.LocalDateTime && certificate.NotAfter > now.LocalDateTime))
{
#if SUPPORTS_CERTIFICATE_GENERATION
using var algorithm = OpenIddictHelpers.CreateRsaKey(size: 4096);
var request = new CertificateRequest(subject, algorithm, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, critical: true));
var certificate = request.CreateSelfSigned(now, now.AddYears(2));
// Note: setting the friendly name is not supported on Unix machines (including Linux and macOS).
// To ensure an exception is not thrown by the property setter, an OS runtime check is used here.
if (OperatingSystem.IsWindows())
{
certificate.FriendlyName = "OpenIddict Server Development Signing Certificate";
}
// Note: CertificateRequest.CreateSelfSigned() doesn't mark the key set associated with the certificate
// as "persisted", which eventually prevents X509Store.Add() from correctly storing the private key.
// To work around this issue, the certificate payload is manually exported and imported back
// into a new X509Certificate2 instance specifying the X509KeyStorageFlags.PersistKeySet flag.
var data = certificate.Export(X509ContentType.Pfx, string.Empty);
try
{
var flags = X509KeyStorageFlags.PersistKeySet;
// Note: macOS requires marking the certificate private key as exportable.
// If this flag is not set, a CryptographicException is thrown at runtime.
if (OperatingSystem.IsMacOS())
{
flags |= X509KeyStorageFlags.Exportable;
}
#if SUPPORTS_CERTIFICATE_LOADER
certificate = X509CertificateLoader.LoadPkcs12(data, string.Empty, flags);
#else
certificate = new X509Certificate2(data, string.Empty, flags);
#endif
certificates.Insert(0, certificate);
}
finally
{
Array.Clear(data, 0, data.Length);
}
store.Add(certificate);
#else
throw new PlatformNotSupportedException(SR.GetResourceString(SR.ID0264));
#endif
}
options.SigningCredentials.AddRange(
from certificate in certificates
let key = new X509SecurityKey(certificate)
select new SigningCredentials(key, SecurityAlgorithms.RsaSha256));
});
return this;
}
/// <summary>
/// Registers a new ephemeral signing key. Ephemeral signing keys are automatically
/// discarded when the application shuts down and payloads signed using this key are
/// automatically invalidated. This method should only be used during development.
/// On production, using a X.509 certificate stored in the machine store is recommended.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEphemeralSigningKey()
=> AddEphemeralSigningKey(SecurityAlgorithms.RsaSha256);
/// <summary>
/// Registers a new ephemeral signing key. Ephemeral signing keys are automatically
/// discarded when the application shuts down and payloads signed using this key are
/// automatically invalidated. This method should only be used during development.
/// On production, using a X.509 certificate stored in the machine store is recommended.
/// </summary>
/// <param name="algorithm">The algorithm associated with the signing key.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddEphemeralSigningKey(string algorithm)
{
ArgumentException.ThrowIfNullOrEmpty(algorithm);
return algorithm switch
{
SecurityAlgorithms.RsaSha256 or
SecurityAlgorithms.RsaSha384 or
SecurityAlgorithms.RsaSha512 or
SecurityAlgorithms.RsaSha256Signature or
SecurityAlgorithms.RsaSha384Signature or
SecurityAlgorithms.RsaSha512Signature or
SecurityAlgorithms.RsaSsaPssSha256 or
SecurityAlgorithms.RsaSsaPssSha384 or
SecurityAlgorithms.RsaSsaPssSha512 or
SecurityAlgorithms.RsaSsaPssSha256Signature or
SecurityAlgorithms.RsaSsaPssSha384Signature or
SecurityAlgorithms.RsaSsaPssSha512Signature
=> AddSigningCredentials(new SigningCredentials(new RsaSecurityKey(
OpenIddictHelpers.CreateRsaKey(size: 4096)), algorithm)),
#if SUPPORTS_ECDSA
SecurityAlgorithms.EcdsaSha256 or
SecurityAlgorithms.EcdsaSha256Signature
=> AddSigningCredentials(new SigningCredentials(new ECDsaSecurityKey(
OpenIddictHelpers.CreateEcdsaKey(ECCurve.NamedCurves.nistP256)), algorithm)),
SecurityAlgorithms.EcdsaSha384 or
SecurityAlgorithms.EcdsaSha384Signature
=> AddSigningCredentials(new SigningCredentials(new ECDsaSecurityKey(
OpenIddictHelpers.CreateEcdsaKey(ECCurve.NamedCurves.nistP384)), algorithm)),
SecurityAlgorithms.EcdsaSha512 or
SecurityAlgorithms.EcdsaSha512Signature
=> AddSigningCredentials(new SigningCredentials(new ECDsaSecurityKey(
OpenIddictHelpers.CreateEcdsaKey(ECCurve.NamedCurves.nistP521)), algorithm)),
#else
SecurityAlgorithms.EcdsaSha256 or
SecurityAlgorithms.EcdsaSha384 or
SecurityAlgorithms.EcdsaSha512 or
SecurityAlgorithms.EcdsaSha256Signature or
SecurityAlgorithms.EcdsaSha384Signature or
SecurityAlgorithms.EcdsaSha512Signature
=> throw new PlatformNotSupportedException(SR.GetResourceString(SR.ID0069)),
#endif
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0058))
};
}
/// <summary>
/// Registers a signing certificate.
/// </summary>
/// <param name="certificate">The signing certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(X509Certificate2 certificate)
{
ArgumentNullException.ThrowIfNull(certificate);
// If the certificate is a X.509v3 certificate that specifies at least
// one key usage, ensure that the certificate key can be used for signing.
if (certificate.Version is >= 3)
{
var extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
if (extensions.Count is not 0 && !extensions.Exists(static extension =>
extension.KeyUsages.HasFlag(X509KeyUsageFlags.DigitalSignature)))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0070));
}
}
if (!certificate.HasPrivateKey)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0061));
}
return AddSigningKey(new X509SecurityKey(certificate));
}
/// <summary>
/// Registers a signing certificate retrieved from an embedded resource.
/// </summary>
/// <param name="assembly">The assembly containing the certificate.</param>
/// <param name="resource">The name of the embedded resource.</param>
/// <param name="password">The password used to open the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(Assembly assembly, string resource, string? password)
#if SUPPORTS_EPHEMERAL_KEY_SETS
// Note: ephemeral key sets are currently not supported on macOS.
=> AddSigningCertificate(assembly, resource, password, OperatingSystem.IsMacOS() ?
X509KeyStorageFlags.MachineKeySet :
X509KeyStorageFlags.EphemeralKeySet);
#else
=> AddSigningCertificate(assembly, resource, password, X509KeyStorageFlags.MachineKeySet);
#endif
/// <summary>
/// Registers a signing certificate retrieved from an embedded resource.
/// </summary>
/// <param name="assembly">The assembly containing the certificate.</param>
/// <param name="resource">The name of the embedded resource.</param>
/// <param name="password">The password used to open the certificate.</param>
/// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(
Assembly assembly, string resource,
string? password, X509KeyStorageFlags flags)
{
ArgumentNullException.ThrowIfNull(assembly);
ArgumentException.ThrowIfNullOrEmpty(resource);
using var stream = assembly.GetManifestResourceStream(resource) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0064));
return AddSigningCertificate(stream, password, flags);
}
/// <summary>
/// Registers a signing certificate extracted from a stream.
/// </summary>
/// <param name="stream">The stream containing the certificate.</param>
/// <param name="password">The password used to open the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(Stream stream, string? password)
#if SUPPORTS_EPHEMERAL_KEY_SETS
// Note: ephemeral key sets are currently not supported on macOS.
=> AddSigningCertificate(stream, password, OperatingSystem.IsMacOS() ?
X509KeyStorageFlags.MachineKeySet :
X509KeyStorageFlags.EphemeralKeySet);
#else
=> AddSigningCertificate(stream, password, X509KeyStorageFlags.MachineKeySet);
#endif
/// <summary>
/// Registers a signing certificate extracted from a stream.
/// </summary>
/// <param name="stream">The stream containing the certificate.</param>
/// <param name="password">The password used to open the certificate.</param>
/// <param name="flags">An enumeration of flags indicating how and where to store the private key of the certificate.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(Stream stream, string? password, X509KeyStorageFlags flags)
{
ArgumentNullException.ThrowIfNull(stream);
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
#if SUPPORTS_CERTIFICATE_LOADER
var certificate = X509Certificate2.GetCertContentType(buffer.ToArray()) switch
{
X509ContentType.Pkcs12 => X509CertificateLoader.LoadPkcs12(buffer.ToArray(), password, flags),
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0454))
};
#else
var certificate = new X509Certificate2(buffer.ToArray(), password, flags);
#endif
return AddSigningCertificate(certificate);
}
/// <summary>
/// Registers a signing certificate retrieved from the X.509 user or machine store.
/// </summary>
/// <param name="thumbprint">The thumbprint of the certificate used to identify it in the X.509 store.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(string thumbprint)
{
ArgumentException.ThrowIfNullOrEmpty(thumbprint);
return AddSigningCertificate(
GetCertificate(StoreLocation.CurrentUser, thumbprint) ??
GetCertificate(StoreLocation.LocalMachine, thumbprint) ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint)
{
using var store = new X509Store(StoreName.My, location);
store.Open(OpenFlags.ReadOnly);
return store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.Cast<X509Certificate2>()
.SingleOrDefault();
}
}
/// <summary>
/// Registers a signing certificate retrieved from the specified X.509 store.
/// </summary>
/// <param name="thumbprint">The thumbprint of the certificate used to identify it in the X.509 store.</param>
/// <param name="name">The name of the X.509 store.</param>
/// <param name="location">The location of the X.509 store.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificate(string thumbprint, StoreName name, StoreLocation location)
{
ArgumentException.ThrowIfNullOrEmpty(thumbprint);
using var store = new X509Store(name, location);
store.Open(OpenFlags.ReadOnly);
return AddSigningCertificate(
store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false)
.Cast<X509Certificate2>()
.SingleOrDefault() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066)));
}
/// <summary>
/// Registers multiple signing certificates.
/// </summary>
/// <param name="certificates">The signing certificates.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AddSigningCertificates(IEnumerable<X509Certificate2> certificates)
{
ArgumentNullException.ThrowIfNull(certificates);
return certificates.Aggregate(this, static (builder, certificate) => builder.AddSigningCertificate(certificate));
}
/// <summary>
/// Enables authorization code flow support. For more information
/// about this specific OAuth 2.0/OpenID Connect flow, visit
/// https://tools.ietf.org/html/rfc6749#section-4.1 and
/// http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowAuthorizationCodeFlow()
=> Configure(options =>
{
options.GrantTypes.Add(GrantTypes.AuthorizationCode);
options.ResponseTypes.Add(ResponseTypes.Code);
});
/// <summary>
/// Enables client credentials flow support. For more information about this
/// specific OAuth 2.0 flow, visit https://tools.ietf.org/html/rfc6749#section-4.4.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowClientCredentialsFlow()
=> Configure(options => options.GrantTypes.Add(GrantTypes.ClientCredentials));
/// <summary>
/// Enables custom grant type support.
/// </summary>
/// <param name="type">The grant type associated with the flow.</param>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public OpenIddictServerBuilder AllowCustomFlow(string type)
{
ArgumentException.ThrowIfNullOrEmpty(type);
return Configure(options => options.GrantTypes.Add(type));
}
/// <summary>
/// Enables device authorization flow support. For more information about this
/// specific OAuth 2.0 flow, visit https://tools.ietf.org/html/rfc8628.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowDeviceAuthorizationFlow()
=> Configure(options => options.GrantTypes.Add(GrantTypes.DeviceCode));
/// <summary>
/// Enables hybrid flow support. For more information
/// about this specific OpenID Connect flow, visit
/// http://openid.net/specs/openid-connect-core-1_0.html#HybridFlowAuth.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowHybridFlow()
=> Configure(options =>
{
options.GrantTypes.Add(GrantTypes.AuthorizationCode);
options.GrantTypes.Add(GrantTypes.Implicit);
options.ResponseTypes.Add(ResponseTypes.Code + ' ' + ResponseTypes.IdToken);
options.ResponseTypes.Add(ResponseTypes.Code + ' ' + ResponseTypes.IdToken + ' ' + ResponseTypes.Token);
options.ResponseTypes.Add(ResponseTypes.Code + ' ' + ResponseTypes.Token);
});
/// <summary>
/// Enables implicit flow support. For more information
/// about this specific OAuth 2.0/OpenID Connect flow, visit
/// https://tools.ietf.org/html/rfc6749#section-4.2 and
/// http://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth.
/// </summary>
/// <remarks>
/// Note: the implicit flow is not recommended for new applications due to
/// its inherent limitations and should only be used in legacy scenarios.
/// When possible, consider using the authorization code flow instead.
/// </remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowImplicitFlow()
=> Configure(options =>
{
options.GrantTypes.Add(GrantTypes.Implicit);
options.ResponseTypes.Add(ResponseTypes.IdToken);
options.ResponseTypes.Add(ResponseTypes.IdToken + ' ' + ResponseTypes.Token);
options.ResponseTypes.Add(ResponseTypes.Token);
});
/// <summary>
/// Enables none flow support. For more information about this specific OAuth 2.0 flow,
/// visit https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#none.
/// </summary>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowNoneFlow()
=> Configure(options => options.ResponseTypes.Add(ResponseTypes.None));
/// <summary>
/// Enables password flow support. For more information about this specific
/// OAuth 2.0 flow, visit https://tools.ietf.org/html/rfc6749#section-4.3.
/// </summary>
/// <remarks>
/// Note: the password flow is not recommended for new applications due to its
/// inherent limitations and should only be used in legacy scenarios. When possible,
/// consider using an interactive user flow like the authorization code flow instead.
/// </remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder AllowPasswordFlow()
=> Configure(options => options.GrantTypes.Add(GrantTypes.Password));
/// <summary>
/// Enables refresh token flow support. For more information about this
/// specific OAuth 2.0 flow, visit https://tools.ietf.org/html/rfc6749#section-6.