forked from openiddict/openiddict-core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOpenIddictServerHandlers.cs
More file actions
5931 lines (4978 loc) · 273 KB
/
OpenIddictServerHandlers.cs
File metadata and controls
5931 lines (4978 loc) · 273 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.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace OpenIddict.Server;
[EditorBrowsable(EditorBrowsableState.Never)]
public static partial class OpenIddictServerHandlers
{
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Top-level request processing:
*/
InferEndpointType.Descriptor,
/*
* Authentication processing:
*/
ValidateAuthenticationDemand.Descriptor,
EvaluateValidatedTokens.Descriptor,
ResolveValidatedTokens.Descriptor,
ValidateRequiredTokens.Descriptor,
ValidateClientAssertion.Descriptor,
ValidateClientAssertionWellknownClaims.Descriptor,
ValidateClientAssertionIssuer.Descriptor,
ValidateClientAssertionAudience.Descriptor,
ValidateClientId.Descriptor,
ValidateClientType.Descriptor,
ValidateClientSecret.Descriptor,
ValidateClientCertificate.Descriptor,
ValidateRequestToken.Descriptor,
ValidateRequestTokenType.Descriptor,
ValidateAccessToken.Descriptor,
ValidateAuthorizationCode.Descriptor,
ValidateDeviceCode.Descriptor,
ValidateGenericToken.Descriptor,
ValidateIdentityToken.Descriptor,
ValidateRefreshToken.Descriptor,
ValidateSubjectToken.Descriptor,
ValidateActorToken.Descriptor,
ValidateUserCode.Descriptor,
ResolveHostAuthenticationProperties.Descriptor,
ReformatValidatedTokens.Descriptor,
/*
* Challenge processing:
*/
ValidateChallengeDemand.Descriptor,
AttachDefaultChallengeError.Descriptor,
RejectDeviceCodeEntry.Descriptor,
RejectUserCodeEntry.Descriptor,
AttachCustomChallengeParameters.Descriptor,
/*
* Sign-in processing:
*/
ValidateSignInDemand.Descriptor,
RedeemTokenEntry.Descriptor,
RestoreInternalClaims.Descriptor,
AttachHostProperties.Descriptor,
AttachDefaultScopes.Descriptor,
AttachDefaultPresenters.Descriptor,
InferResources.Descriptor,
EvaluateGeneratedTokens.Descriptor,
AttachAuthorization.Descriptor,
PrepareAccessTokenPrincipal.Descriptor,
PrepareAuthorizationCodePrincipal.Descriptor,
PrepareDeviceCodePrincipal.Descriptor,
PrepareIssuedTokenPrincipal.Descriptor,
PrepareRequestTokenPrincipal.Descriptor,
PrepareRefreshTokenPrincipal.Descriptor,
PrepareIdentityTokenPrincipal.Descriptor,
PrepareUserCodePrincipal.Descriptor,
GenerateAccessToken.Descriptor,
GenerateAuthorizationCode.Descriptor,
GenerateDeviceCode.Descriptor,
GenerateIssuedToken.Descriptor,
GenerateRequestToken.Descriptor,
GenerateRefreshToken.Descriptor,
AttachDeviceCodeIdentifier.Descriptor,
UpdateReferenceDeviceCodeEntry.Descriptor,
AttachTokenDigests.Descriptor,
GenerateUserCode.Descriptor,
GenerateIdentityToken.Descriptor,
BeautifyGeneratedTokens.Descriptor,
AttachSignInParameters.Descriptor,
AttachCustomSignInParameters.Descriptor,
/*
* Sign-out processing:
*/
ValidateSignOutDemand.Descriptor,
RedeemLogoutTokenEntry.Descriptor,
AttachCustomSignOutParameters.Descriptor,
/*
* Error processing:
*/
AttachErrorParameters.Descriptor,
AttachCustomErrorParameters.Descriptor,
.. Authentication.DefaultHandlers,
.. Device.DefaultHandlers,
.. Discovery.DefaultHandlers,
.. Exchange.DefaultHandlers,
.. Introspection.DefaultHandlers,
.. Protection.DefaultHandlers,
.. Revocation.DefaultHandlers,
.. Session.DefaultHandlers,
.. UserInfo.DefaultHandlers
];
/// <summary>
/// Contains the logic responsible for inferring the endpoint type from the request URI.
/// </summary>
public sealed class InferEndpointType : IOpenIddictServerHandler<ProcessRequestContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessRequestContext>()
.UseSingletonHandler<InferEndpointType>()
.SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessRequestContext context)
{
ArgumentNullException.ThrowIfNull(context);
// If the base or request URIs couldn't be resolved, don't try to infer the endpoint type.
if (context is not { BaseUri.IsAbsoluteUri: true, RequestUri.IsAbsoluteUri: true })
{
return ValueTask.CompletedTask;
}
context.EndpointType =
Matches(context.Options.AuthorizationEndpointUris) ? OpenIddictServerEndpointType.Authorization :
Matches(context.Options.ConfigurationEndpointUris) ? OpenIddictServerEndpointType.Configuration :
Matches(context.Options.DeviceAuthorizationEndpointUris) ? OpenIddictServerEndpointType.DeviceAuthorization :
Matches(context.Options.EndSessionEndpointUris) ? OpenIddictServerEndpointType.EndSession :
Matches(context.Options.EndUserVerificationEndpointUris) ? OpenIddictServerEndpointType.EndUserVerification :
Matches(context.Options.IntrospectionEndpointUris) ? OpenIddictServerEndpointType.Introspection :
Matches(context.Options.JsonWebKeySetEndpointUris) ? OpenIddictServerEndpointType.JsonWebKeySet :
Matches(context.Options.PushedAuthorizationEndpointUris) ? OpenIddictServerEndpointType.PushedAuthorization :
Matches(context.Options.RevocationEndpointUris) ? OpenIddictServerEndpointType.Revocation :
Matches(context.Options.TokenEndpointUris) ? OpenIddictServerEndpointType.Token :
Matches(context.Options.UserInfoEndpointUris) ? OpenIddictServerEndpointType.UserInfo :
OpenIddictServerEndpointType.Unknown;
if (context.EndpointType is not OpenIddictServerEndpointType.Unknown)
{
context.Logger.LogInformation(6053, SR.GetResourceString(SR.ID6053), context.EndpointType);
}
return ValueTask.CompletedTask;
bool Matches(IReadOnlyList<Uri> candidates)
{
for (var index = 0; index < candidates.Count; index++)
{
var candidate = candidates[index];
if (candidate.IsAbsoluteUri)
{
if (Equals(candidate, context.RequestUri))
{
return true;
}
}
else
{
var uri = OpenIddictHelpers.CreateAbsoluteUri(context.BaseUri, candidate);
if (!OpenIddictHelpers.IsImplicitFileUri(uri) &&
OpenIddictHelpers.IsBaseOf(context.BaseUri, uri) && Equals(uri, context.RequestUri))
{
return true;
}
}
}
return false;
}
static bool Equals(Uri left, Uri right) =>
string.Equals(left.Scheme, right.Scheme, StringComparison.OrdinalIgnoreCase) &&
string.Equals(left.Host, right.Host, StringComparison.OrdinalIgnoreCase) &&
left.Port == right.Port &&
// Note: paths are considered equivalent even if the casing isn't identical or if one of the two
// paths only differs by a trailing slash, which matches the classical behavior seen on ASP.NET,
// Microsoft.Owin/Katana and ASP.NET Core. Developers who prefer a different behavior can remove
// this handler and replace it by a custom version implementing a more strict comparison logic.
(string.Equals(left.AbsolutePath, right.AbsolutePath, StringComparison.OrdinalIgnoreCase) ||
(left.AbsolutePath.Length == right.AbsolutePath.Length + 1 &&
left.AbsolutePath.StartsWith(right.AbsolutePath, StringComparison.OrdinalIgnoreCase) &&
left.AbsolutePath[^1] is '/') ||
(right.AbsolutePath.Length == left.AbsolutePath.Length + 1 &&
right.AbsolutePath.StartsWith(left.AbsolutePath, StringComparison.OrdinalIgnoreCase) &&
right.AbsolutePath[^1] is '/'));
}
}
/// <summary>
/// Contains the logic responsible for rejecting authentication demands made from unsupported endpoints.
/// </summary>
public sealed class ValidateAuthenticationDemand : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<ValidateAuthenticationDemand>()
.SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
return context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization or OpenIddictServerEndpointType.DeviceAuthorization or
OpenIddictServerEndpointType.EndSession or OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.Introspection or OpenIddictServerEndpointType.PushedAuthorization or
OpenIddictServerEndpointType.Revocation or OpenIddictServerEndpointType.Token or
OpenIddictServerEndpointType.UserInfo
=> default,
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0002)),
};
}
}
/// <summary>
/// Contains the logic responsible for selecting the token types that should be validated.
/// </summary>
public sealed class EvaluateValidatedTokens : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<EvaluateValidatedTokens>()
.SetOrder(ValidateAuthenticationDemand.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
(context.ExtractAccessToken,
context.RequireAccessToken,
context.ValidateAccessToken,
context.RejectAccessToken) = context.EndpointType switch
{
// The userinfo endpoint requires sending a valid access token.
OpenIddictServerEndpointType.UserInfo => (true, true, true, true),
_ => (false, false, false, false)
};
(context.ExtractActorToken,
context.RequireActorToken,
context.ValidateActorToken,
context.RejectActorToken) = context.EndpointType switch
{
// The actor token is optional for the token exchange grant.
OpenIddictServerEndpointType.Token when context.Request.IsTokenExchangeGrantType()
=> (true, false, true, true),
_ => (false, false, false, false)
};
(context.ExtractAuthorizationCode,
context.RequireAuthorizationCode,
context.ValidateAuthorizationCode,
context.RejectAuthorizationCode) = context.EndpointType switch
{
// The authorization code grant requires sending a valid authorization code.
OpenIddictServerEndpointType.Token when context.Request.IsAuthorizationCodeGrantType()
=> (true, true, true, true),
_ => (false, false, false, false)
};
(context.ExtractClientAssertion,
context.RequireClientAssertion,
context.ValidateClientAssertion,
context.RejectClientAssertion) = context.EndpointType switch
{
// Client assertions can be used with all the endpoints that support client authentication.
// By default, client assertions are not required, but they are extracted and validated if
// present and invalid client assertions are always automatically rejected by OpenIddict.
OpenIddictServerEndpointType.DeviceAuthorization or OpenIddictServerEndpointType.Introspection or
OpenIddictServerEndpointType.PushedAuthorization or OpenIddictServerEndpointType.Revocation or
OpenIddictServerEndpointType.Token
=> (true, false, true, true),
_ => (false, false, false, false)
};
(context.ExtractDeviceCode,
context.RequireDeviceCode,
context.ValidateDeviceCode,
context.RejectDeviceCode) = context.EndpointType switch
{
// The device code grant requires sending a valid device code.
OpenIddictServerEndpointType.Token when context.Request.IsDeviceCodeGrantType()
=> (true, true, true, true),
_ => (false, false, false, false)
};
(context.ExtractGenericToken,
context.RequireGenericToken,
context.ValidateGenericToken,
context.RejectGenericToken) = context.EndpointType switch
{
// Tokens received by the introspection and revocation endpoints can be of any supported type.
// Additional token type filtering is typically performed by the endpoint themselves when needed.
OpenIddictServerEndpointType.Introspection or OpenIddictServerEndpointType.Revocation
=> (true, true, true, true),
_ => (false, false, false, false)
};
(context.ExtractIdentityToken,
context.RequireIdentityToken,
context.ValidateIdentityToken,
context.RejectIdentityToken) = context.EndpointType switch
{
// The identity token received by the authorization, end session and pushed
// authorization endpoints are not required and serve as optional hints.
//
// As such, identity token hints are extracted and validated, but
// the authentication demand is not rejected if they are not valid.
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.PushedAuthorization
=> (true, false, true, false),
_ => (false, false, false, false)
};
(context.ExtractRequestToken,
context.RequireRequestToken,
context.ValidateRequestToken,
context.RejectRequestToken) = context.EndpointType switch
{
// Always validate request tokens received by the authorization or end session endpoints.
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndSession => (true, false, true, true),
_ => (false, false, false, false)
};
(context.ExtractRefreshToken,
context.RequireRefreshToken,
context.ValidateRefreshToken,
context.RejectRefreshToken) = context.EndpointType switch
{
// The refresh token grant requires sending a valid refresh token.
OpenIddictServerEndpointType.Token when context.Request.IsRefreshTokenGrantType()
=> (true, true, true, true),
_ => (false, false, false, false)
};
(context.ExtractSubjectToken,
context.RequireSubjectToken,
context.ValidateSubjectToken,
context.RejectSubjectToken) = context.EndpointType switch
{
// The subject token is mandatory for the token exchange grant.
OpenIddictServerEndpointType.Token when context.Request.IsTokenExchangeGrantType()
=> (true, true, true, true),
_ => (false, false, false, false)
};
(context.ExtractUserCode,
context.RequireUserCode,
context.ValidateUserCode,
context.RejectUserCode) = context.EndpointType switch
{
// Note: the end-user verification endpoint can be accessed without specifying a
// user code (that can be later set by the user using a form, for instance).
OpenIddictServerEndpointType.EndUserVerification => (true, false, true, false),
_ => (false, false, false, false)
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for resolving the tokens from the incoming request.
/// </summary>
public sealed class ResolveValidatedTokens : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<ResolveValidatedTokens>()
.SetOrder(EvaluateValidatedTokens.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.AccessToken = context.EndpointType switch
{
OpenIddictServerEndpointType.UserInfo when context.ExtractAccessToken
=> context.Request.AccessToken,
_ => null
};
(context.ActorToken, context.ActorTokenType) = context.EndpointType switch
{
OpenIddictServerEndpointType.Token when context.ExtractActorToken
=> (context.Request.ActorToken, context.Request.ActorTokenType),
_ => (null, null)
};
context.AuthorizationCode = context.EndpointType switch
{
OpenIddictServerEndpointType.Token when context.ExtractAuthorizationCode
=> context.Request.Code,
_ => null
};
(context.ClientAssertion, context.ClientAssertionType) = context.EndpointType switch
{
OpenIddictServerEndpointType.DeviceAuthorization or OpenIddictServerEndpointType.Introspection or
OpenIddictServerEndpointType.PushedAuthorization or OpenIddictServerEndpointType.Revocation or
OpenIddictServerEndpointType.Token
when context.ExtractClientAssertion
=> (context.Request.ClientAssertion, context.Request.ClientAssertionType),
_ => (null, null)
};
context.DeviceCode = context.EndpointType switch
{
OpenIddictServerEndpointType.Token when context.ExtractDeviceCode
=> context.Request.DeviceCode,
_ => null
};
(context.GenericToken, context.GenericTokenTypeHint) = context.EndpointType switch
{
OpenIddictServerEndpointType.Introspection or
OpenIddictServerEndpointType.Revocation when context.ExtractGenericToken
=> (context.Request.Token, context.Request.TokenTypeHint),
_ => (null, null)
};
context.IdentityToken = context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization or
OpenIddictServerEndpointType.EndSession or
OpenIddictServerEndpointType.PushedAuthorization when context.ExtractIdentityToken
=> context.Request.IdTokenHint,
_ => null
};
context.RequestToken = context.EndpointType switch
{
OpenIddictServerEndpointType.Authorization when
context.ExtractRequestToken &&
context.Request.RequestUri is { Length: > 0 } uri &&
uri.StartsWith(RequestUris.Prefixes.Generic, StringComparison.OrdinalIgnoreCase)
=> uri[RequestUris.Prefixes.Generic.Length..],
OpenIddictServerEndpointType.EndSession when
context.ExtractRequestToken &&
context.Request.RequestUri is { Length: > 0 } uri &&
uri.StartsWith(RequestUris.Prefixes.Generic, StringComparison.OrdinalIgnoreCase)
=> uri[RequestUris.Prefixes.Generic.Length..],
_ => null
};
context.RefreshToken = context.EndpointType switch
{
OpenIddictServerEndpointType.Token when context.ExtractRefreshToken
=> context.Request.RefreshToken,
_ => null
};
(context.SubjectToken, context.SubjectTokenType) = context.EndpointType switch
{
OpenIddictServerEndpointType.Token when context.ExtractSubjectToken
=> (context.Request.SubjectToken, context.Request.SubjectTokenType),
_ => (null, null)
};
context.UserCode = context.EndpointType switch
{
OpenIddictServerEndpointType.EndUserVerification when context.ExtractUserCode
=> context.Request.UserCode,
_ => null
};
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for rejecting authentication demands that lack required tokens.
/// </summary>
public sealed class ValidateRequiredTokens : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<ValidateRequiredTokens>()
// Note: this handler is registered with a high gap to allow handlers
// that do token extraction to be executed before this handler runs.
.SetOrder(ResolveValidatedTokens.Descriptor.Order + 50_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
if ((context.RequireAccessToken && string.IsNullOrEmpty(context.AccessToken)) ||
(context.RequireActorToken && string.IsNullOrEmpty(context.ActorToken)) ||
(context.RequireAuthorizationCode && string.IsNullOrEmpty(context.AuthorizationCode)) ||
(context.RequireClientAssertion && string.IsNullOrEmpty(context.ClientAssertion)) ||
(context.RequireDeviceCode && string.IsNullOrEmpty(context.DeviceCode)) ||
(context.RequireGenericToken && string.IsNullOrEmpty(context.GenericToken)) ||
(context.RequireIdentityToken && string.IsNullOrEmpty(context.IdentityToken)) ||
(context.RequireRefreshToken && string.IsNullOrEmpty(context.RefreshToken)) ||
(context.RequireRequestToken && string.IsNullOrEmpty(context.RequestToken)) ||
(context.RequireSubjectToken && string.IsNullOrEmpty(context.SubjectToken)) ||
(context.RequireUserCode && string.IsNullOrEmpty(context.UserCode)))
{
context.Reject(
error: Errors.MissingToken,
description: SR.GetResourceString(SR.ID2000),
uri: SR.FormatID8000(SR.ID2000));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for validating the client assertion resolved from the context.
/// </summary>
public sealed class ValidateClientAssertion : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
private readonly IOpenIddictServerDispatcher _dispatcher;
public ValidateClientAssertion(IOpenIddictServerDispatcher dispatcher)
=> _dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireClientAssertionValidated>()
.UseScopedHandler<ValidateClientAssertion>()
.SetOrder(ValidateRequiredTokens.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (string.IsNullOrEmpty(context.ClientAssertion))
{
return;
}
var notification = new ValidateTokenContext(context.Transaction)
{
// Note: for client authentication assertions, audience validation is enforced by a specialized handler.
DisableAudienceValidation = true,
DisablePresenterValidation = true,
Token = context.ClientAssertion,
TokenFormat = context.ClientAssertionType switch
{
ClientAssertionTypes.JwtBearer => TokenFormats.Private.JsonWebToken,
ClientAssertionTypes.Saml2Bearer => TokenFormats.Private.Saml2,
_ => null
},
ValidTokenTypes = { TokenTypeIdentifiers.Private.ClientAssertion }
};
await _dispatcher.DispatchAsync(notification);
if (notification.IsRequestHandled)
{
context.HandleRequest();
return;
}
else if (notification.IsRequestSkipped)
{
context.SkipRequest();
return;
}
else if (notification.IsRejected)
{
if (context.RejectClientAssertion)
{
context.Reject(
error: notification.Error ?? Errors.InvalidClient,
description: notification.ErrorDescription,
uri: notification.ErrorUri);
return;
}
return;
}
context.ClientAssertionPrincipal = notification.Principal;
}
}
/// <summary>
/// Contains the logic responsible for validating the well-known claims contained in the client assertion principal.
/// </summary>
public sealed class ValidateClientAssertionWellknownClaims : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireClientAssertionPrincipal>()
.UseSingletonHandler<ValidateClientAssertionWellknownClaims>()
.SetOrder(ValidateClientAssertion.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.ClientAssertionPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
foreach (var group in context.ClientAssertionPrincipal.Claims
.GroupBy(static claim => claim.Type)
.ToDictionary(static group => group.Key, group => group.ToList())
.Where(static group => !ValidateClaimGroup(group.Key, group.Value)))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2171(group.Key),
uri: SR.FormatID8000(SR.ID2171));
return ValueTask.CompletedTask;
}
// Client assertions MUST contain an "iss" claim. For more information,
// see https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
// and https://datatracker.ietf.org/doc/html/rfc7523#section-3.
if (!context.ClientAssertionPrincipal.HasClaim(Claims.Issuer))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2172(Claims.Issuer),
uri: SR.FormatID8000(SR.ID2172));
return ValueTask.CompletedTask;
}
// Client assertions MUST contain a "sub" claim. For more information,
// see https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
// and https://datatracker.ietf.org/doc/html/rfc7523#section-3.
if (!context.ClientAssertionPrincipal.HasClaim(Claims.Subject))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2172(Claims.Subject),
uri: SR.FormatID8000(SR.ID2172));
return ValueTask.CompletedTask;
}
// Client assertions MUST contain an "aud" claim. For more information,
// see https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
// and https://datatracker.ietf.org/doc/html/rfc7523#section-3.
if (!context.ClientAssertionPrincipal.HasClaim(Claims.Audience))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2172(Claims.Audience),
uri: SR.FormatID8000(SR.ID2172));
return ValueTask.CompletedTask;
}
// Client assertions MUST contain contain a "exp" claim. For more information,
// see https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
// and https://datatracker.ietf.org/doc/html/rfc7523#section-3.
if (!context.ClientAssertionPrincipal.HasClaim(Claims.ExpiresAt))
{
context.Reject(
error: Errors.InvalidRequest,
description: SR.FormatID2172(Claims.ExpiresAt),
uri: SR.FormatID8000(SR.ID2172));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
static bool ValidateClaimGroup(string name, List<Claim> values) => name switch
{
// The following claims MUST be represented as unique strings.
//
// Important: client assertions with multiple audiences was initially deliberately supported by
// the OpenID Connect and Assertion Framework for OAuth 2.0 Client Authentication specifications.
// Since 2025, using multiple audiences is no longer allowed for security reasons. As such, the
// "aud" claim present in client assertions MUST always be represented as a single string.
//
// See https://www.ietf.org/archive/id/draft-ietf-oauth-rfc7523bis-01.html#section-4 for more information.
Claims.Audience or Claims.AuthorizedParty or Claims.Issuer or Claims.JwtId or Claims.Subject
=> values is [{ ValueType: ClaimValueTypes.String }],
// The following claims MUST be represented as unique numeric dates.
Claims.ExpiresAt or Claims.IssuedAt or Claims.NotBefore
=> values is [{ ValueType: ClaimValueTypes.Integer or ClaimValueTypes.Integer32 or
ClaimValueTypes.Integer64 or ClaimValueTypes.Double or
ClaimValueTypes.UInteger32 or ClaimValueTypes.UInteger64 }],
// Claims that are not in the well-known list can be of any type.
_ => true
};
}
}
/// <summary>
/// Contains the logic responsible for validating the issuer contained in the client assertion principal.
/// </summary>
public sealed class ValidateClientAssertionIssuer : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireClientAssertionPrincipal>()
.UseSingletonHandler<ValidateClientAssertionIssuer>()
.SetOrder(ValidateClientAssertionWellknownClaims.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.ClientAssertionPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Ensure the subject represented by the client assertion matches its issuer.
var (issuer, subject) = (
context.ClientAssertionPrincipal.GetClaim(Claims.Issuer),
context.ClientAssertionPrincipal.GetClaim(Claims.Subject));
if (!string.Equals(issuer, subject, StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidGrant,
description: SR.FormatID2173(Claims.Subject),
uri: SR.FormatID8000(SR.ID2173));
return ValueTask.CompletedTask;
}
// If a client identifier was also specified in the request, ensure the
// value matches the application represented by the client assertion.
if (!string.IsNullOrEmpty(context.ClientId))
{
if (!string.Equals(context.ClientId, issuer, StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidGrant,
description: SR.FormatID2173(Claims.Issuer),
uri: SR.FormatID8000(SR.ID2173));
return ValueTask.CompletedTask;
}
if (!string.Equals(context.ClientId, subject, StringComparison.Ordinal))
{
context.Reject(
error: Errors.InvalidGrant,
description: SR.FormatID2173(Claims.Subject),
uri: SR.FormatID8000(SR.ID2173));
return ValueTask.CompletedTask;
}
}
// Otherwise, use the issuer resolved from the client assertion principal as the client identifier.
else if (context.Request is OpenIddictRequest request)
{
request.ClientId = context.ClientAssertionPrincipal.GetClaim(Claims.Issuer);
}
return ValueTask.CompletedTask;
}
}
/// <summary>
/// Contains the logic responsible for validating the audience contained in the client assertion principal.
/// </summary>
public sealed class ValidateClientAssertionAudience : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.AddFilter<RequireClientAssertionPrincipal>()
.UseSingletonHandler<ValidateClientAssertionAudience>()
.SetOrder(ValidateClientAssertionIssuer.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
Debug.Assert(context.ClientAssertionPrincipal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Important: client assertions with multiple audiences was initially deliberately supported by
// the OpenID Connect and Assertion Framework for OAuth 2.0 Client Authentication specifications.
// Since 2025, using multiple audiences is no longer allowed for security reasons: as such, a single
// audience is allowed here and an exception is thrown if multiple claims are present in the principal.
//
// See https://www.ietf.org/archive/id/draft-ietf-oauth-rfc7523bis-01.html#section-4 for more information.
var audience = context.ClientAssertionPrincipal.GetClaim(Claims.Audience);
if (string.IsNullOrEmpty(audience) ||
!Uri.TryCreate(audience, UriKind.Absolute, out Uri? uri) || OpenIddictHelpers.IsImplicitFileUri(uri))
{
context.Reject(
error: Errors.InvalidGrant,
description: SR.FormatID2172(Claims.Audience),
uri: SR.FormatID8000(SR.ID2172));
return ValueTask.CompletedTask;
}
// Throw an exception if the issuer cannot be retrieved or is not valid.
var issuer = context.Options.Issuer ?? context.BaseUri;
if (issuer is not { IsAbsoluteUri: true })
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0496));
}
if (!UriEquals(uri, issuer))
{
context.Reject(
error: Errors.InvalidGrant,
description: SR.FormatID2173(Claims.Audience),
uri: SR.FormatID8000(SR.ID2173));
return ValueTask.CompletedTask;
}
return ValueTask.CompletedTask;
static bool UriEquals(Uri left, Uri right)
{
if (string.Equals(left.AbsolutePath, right.AbsolutePath, StringComparison.Ordinal))
{
return true;
}
// Consider the two URIs identical if they only differ by the trailing slash.
if (left.AbsolutePath.Length == right.AbsolutePath.Length + 1 &&
left.AbsolutePath.StartsWith(right.AbsolutePath, StringComparison.Ordinal) &&
left.AbsolutePath[^1] is '/')
{
return true;
}
return right.AbsolutePath.Length == left.AbsolutePath.Length + 1 &&
right.AbsolutePath.StartsWith(left.AbsolutePath, StringComparison.Ordinal) &&
right.AbsolutePath[^1] is '/';
}
}
}
/// <summary>
/// Contains the logic responsible for rejecting authentication demands that use an invalid client_id.
/// </summary>
public sealed class ValidateClientId : IOpenIddictServerHandler<ProcessAuthenticationContext>
{
private readonly IOpenIddictApplicationManager? _applicationManager;
public ValidateClientId(IOpenIddictApplicationManager? applicationManager = null)
=> _applicationManager = applicationManager;
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseScopedHandler(static provider =>
{
// Note: the application manager is only resolved if the degraded mode was not enabled to ensure
// invalid core configuration exceptions are not thrown even if the managers were registered.
var options = provider.GetRequiredService<IOptionsMonitor<OpenIddictServerOptions>>().CurrentValue;
return options.EnableDegradedMode ?
new ValidateClientId() :
new ValidateClientId(provider.GetService<IOpenIddictApplicationManager>() ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)));
})
.SetOrder(ValidateClientAssertionAudience.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ProcessAuthenticationContext context)
{
ArgumentNullException.ThrowIfNull(context);
// Don't validate the client identifier on endpoints that don't support client identification.
if (context.EndpointType is OpenIddictServerEndpointType.EndUserVerification or
OpenIddictServerEndpointType.UserInfo)
{
return;
}
if (string.IsNullOrEmpty(context.ClientId))
{
switch (context.EndpointType)
{
// Note: support for the client_id parameter was only added in the second draft of the