/
OpenIddictServerHandlers.Protection.cs
1433 lines (1214 loc) · 69.2 KB
/
OpenIddictServerHandlers.Protection.cs
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.Diagnostics;
using System.Globalization;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace OpenIddict.Server;
public static partial class OpenIddictServerHandlers
{
public static class Protection
{
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } = ImmutableArray.Create(
/*
* Token validation:
*/
ResolveTokenValidationParameters.Descriptor,
ValidateReferenceTokenIdentifier.Descriptor,
ValidateIdentityModelToken.Descriptor,
NormalizeScopeClaims.Descriptor,
MapInternalClaims.Descriptor,
RestoreReferenceTokenProperties.Descriptor,
ValidatePrincipal.Descriptor,
ValidateExpirationDate.Descriptor,
ValidateTokenEntry.Descriptor,
ValidateAuthorizationEntry.Descriptor,
/*
* Token generation:
*/
AttachSecurityCredentials.Descriptor,
CreateTokenEntry.Descriptor,
GenerateIdentityModelToken.Descriptor,
ConvertReferenceToken.Descriptor,
BeautifyToken.Descriptor);
/// <summary>
/// Contains the logic responsible of resolving the validation parameters used to validate tokens.
/// </summary>
public class ResolveTokenValidationParameters : IOpenIddictServerHandler<ValidateTokenContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.UseSingletonHandler<ResolveTokenValidationParameters>()
.SetOrder(int.MinValue + 100_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var parameters = context.Options.TokenValidationParameters.Clone();
parameters.ValidIssuer ??= context.Issuer?.AbsoluteUri;
parameters.ValidateIssuer = !string.IsNullOrEmpty(parameters.ValidIssuer);
parameters.ValidTypes = context.ValidTokenTypes.Count switch
{
// If no specific token type is expected, accept all token types at this stage.
// Additional filtering can be made based on the resolved/actual token type.
0 => null,
// Otherwise, map the token types to their JWT public or internal representation.
_ => context.ValidTokenTypes.SelectMany(type => type switch
{
// For access tokens, both "at+jwt" and "application/at+jwt" are valid.
TokenTypeHints.AccessToken => new[]
{
JsonWebTokenTypes.AccessToken,
JsonWebTokenTypes.Prefixes.Application + JsonWebTokenTypes.AccessToken
},
// For identity tokens, both "JWT" and "application/jwt" are valid.
TokenTypeHints.IdToken => new[]
{
JsonWebTokenTypes.IdentityToken,
JsonWebTokenTypes.Prefixes.Application + JsonWebTokenTypes.IdentityToken
},
// For authorization codes, only the short "oi_auc+jwt" form is valid.
TokenTypeHints.AuthorizationCode => new[] { JsonWebTokenTypes.Private.AuthorizationCode },
// For device codes, only the short "oi_dvc+jwt" form is valid.
TokenTypeHints.DeviceCode => new[] { JsonWebTokenTypes.Private.DeviceCode },
// For refresh tokens, only the short "oi_reft+jwt" form is valid.
TokenTypeHints.RefreshToken => new[] { JsonWebTokenTypes.Private.RefreshToken },
// For user codes, only the short "oi_usrc+jwt" form is valid.
TokenTypeHints.UserCode => new[] { JsonWebTokenTypes.Private.UserCode },
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0003))
})
};
context.SecurityTokenHandler = context.Options.JsonWebTokenHandler;
context.TokenValidationParameters = parameters;
return default;
}
}
/// <summary>
/// Contains the logic responsible of validating reference token identifiers.
/// Note: this handler is not used when the degraded mode is enabled.
/// </summary>
public class ValidateReferenceTokenIdentifier : IOpenIddictServerHandler<ValidateTokenContext>
{
private readonly IOpenIddictTokenManager _tokenManager;
public ValidateReferenceTokenIdentifier() => throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
public ValidateReferenceTokenIdentifier(IOpenIddictTokenManager tokenManager)
=> _tokenManager = tokenManager;
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.AddFilter<RequireDegradedModeDisabled>()
.AddFilter<RequireTokenStorageEnabled>()
.UseScopedHandler<ValidateReferenceTokenIdentifier>()
.SetOrder(ResolveTokenValidationParameters.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
public async ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var token = context.Token.Length switch
{
// 12 may correspond to a normalized user code and 43 to any
// other base64url-encoded 256-bit reference token identifier.
12 or 43 => await _tokenManager.FindByReferenceIdAsync(context.Token),
// A value higher than 12 (but lower than 50) may correspond to a user code
// containing dashes or any other non-digit character added by the end user.
// In this case, normalize the reference identifier before making the database lookup.
> 12 and < 50 => await _tokenManager.FindByReferenceIdAsync(NormalizeUserCode(context.Token)),
// If the token length differs, the token cannot be a reference token.
_ => null
};
// If the reference token cannot be found, don't return an error to allow another handler to validate it.
if (token is null)
{
return;
}
// If the type associated with the token entry doesn't match one of the expected types, return an error.
if (!(context.ValidTokenTypes.Count switch
{
0 => true, // If no specific token type is expected, accept all token types at this stage.
1 => await _tokenManager.HasTypeAsync(token, context.ValidTokenTypes.ElementAt(0)),
_ => await _tokenManager.HasTypeAsync(token, context.ValidTokenTypes.ToImmutableArray())
}))
{
context.Reject(
error: Errors.InvalidToken,
description: context.ValidTokenTypes.Count switch
{
1 when context.ValidTokenTypes.Contains(TokenTypeHints.AuthorizationCode)
=> SR.GetResourceString(SR.ID2001),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.DeviceCode)
=> SR.GetResourceString(SR.ID2002),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.RefreshToken)
=> SR.GetResourceString(SR.ID2003),
_ => SR.GetResourceString(SR.ID2004)
},
uri: context.ValidTokenTypes.Count switch
{
1 when context.ValidTokenTypes.Contains(TokenTypeHints.AuthorizationCode)
=> SR.FormatID8000(SR.ID2001),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.DeviceCode)
=> SR.FormatID8000(SR.ID2002),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.RefreshToken)
=> SR.FormatID8000(SR.ID2003),
_ => SR.FormatID8000(SR.ID2004),
});
return;
}
var payload = await _tokenManager.GetPayloadAsync(token);
if (string.IsNullOrEmpty(payload))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0026));
}
// Replace the token parameter by the payload resolved from the token entry
// and store the identifier of the reference token so it can be later
// used to restore the properties associated with the token.
context.Token = payload;
context.TokenId = await _tokenManager.GetIdAsync(token);
// Note: unlike other tokens, user codes may be potentially entered manually by users in a web form.
// To make that easier, user codes are generally "beautified" by adding intermediate dashes to
// make them easier to read and type. Since these additional characters are not part of the original
// user codes, non-digit characters are filtered from the reference identifier using this local method.
static string NormalizeUserCode(string token)
{
var builder = new StringBuilder(token);
for (var index = builder.Length - 1; index >= 0; index--)
{
var character = builder[index];
if (character < '0' || character > '9')
{
builder.Remove(index, 1);
}
}
return builder.ToString();
}
}
}
/// <summary>
/// Contains the logic responsible of validating tokens generated using IdentityModel.
/// </summary>
public class ValidateIdentityModelToken : IOpenIddictServerHandler<ValidateTokenContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.UseSingletonHandler<ValidateIdentityModelToken>()
.SetOrder(ValidateReferenceTokenIdentifier.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// If a principal was already attached, don't overwrite it.
if (context.Principal is not null)
{
return default;
}
// If the token cannot be read, don't return an error to allow another handler to validate it.
if (!context.SecurityTokenHandler.CanReadToken(context.Token))
{
return default;
}
// Special endpoints like introspection or revocation use a single parameter to convey
// multiple types of tokens (typically but not limited to access and refresh tokens).
//
// To speed up the token resolution process, the client can send a "token_type_hint"
// containing the type of the token: if the parameter doesn't match the actual type,
// the authorization server MUST use a fallback mechanism to determine whether the
// token can be introspected or revoked even if it's of a different type.
//
// This logic is not used by OpenIddict for IdentityModel tokens, as processing
// tokens of different type doesn't require re-parsing and re-validating them
// multiple times. As such, the "token_type_hint" parameter is only used in the
// Data Protection integration package and is ignored for IdentityModel tokens.
//
// For more information, see https://datatracker.ietf.org/doc/html/rfc7009#section-2.1
// and https://datatracker.ietf.org/doc/html/rfc7662#section-2.1.
var result = context.SecurityTokenHandler.ValidateToken(context.Token, context.TokenValidationParameters);
if (!result.IsValid)
{
context.Logger.LogTrace(result.Exception, SR.GetResourceString(SR.ID6000), context.Token);
context.Reject(
error: Errors.InvalidToken,
description: result.Exception switch
{
SecurityTokenInvalidTypeException => context.ValidTokenTypes.Count switch
{
1 when context.ValidTokenTypes.Contains(TokenTypeHints.AuthorizationCode)
=> SR.GetResourceString(SR.ID2005),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.DeviceCode)
=> SR.GetResourceString(SR.ID2006),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.RefreshToken)
=> SR.GetResourceString(SR.ID2007),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.AccessToken)
=> SR.GetResourceString(SR.ID2008),
_ => SR.GetResourceString(SR.ID2089)
},
SecurityTokenInvalidIssuerException => SR.GetResourceString(SR.ID2088),
SecurityTokenSignatureKeyNotFoundException => SR.GetResourceString(SR.ID2090),
SecurityTokenInvalidSignatureException => SR.GetResourceString(SR.ID2091),
_ => SR.GetResourceString(SR.ID2004)
},
uri: result.Exception switch
{
SecurityTokenInvalidTypeException => context.ValidTokenTypes.Count switch
{
1 when context.ValidTokenTypes.Contains(TokenTypeHints.AuthorizationCode)
=> SR.FormatID8000(SR.ID2005),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.DeviceCode)
=> SR.FormatID8000(SR.ID2006),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.RefreshToken)
=> SR.FormatID8000(SR.ID2007),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.AccessToken)
=> SR.FormatID8000(SR.ID2008),
_ => SR.FormatID8000(SR.ID2089)
},
SecurityTokenInvalidIssuerException => SR.FormatID8000(SR.ID2088),
SecurityTokenSignatureKeyNotFoundException => SR.FormatID8000(SR.ID2090),
SecurityTokenInvalidSignatureException => SR.FormatID8000(SR.ID2091),
_ => SR.FormatID8000(SR.ID2004)
});
return default;
}
// Get the JWT token. If the token is encrypted using JWE, retrieve the inner token.
var token = (JsonWebToken) result.SecurityToken;
if (token.InnerToken is not null)
{
token = token.InnerToken;
}
// Attach the principal extracted from the token to the parent event context and store
// the token type (resolved from "typ" or "token_usage") as a special private claim.
context.Principal = new ClaimsPrincipal(result.ClaimsIdentity).SetTokenType(result.TokenType switch
{
null or { Length: 0 } => throw new InvalidOperationException(SR.GetResourceString(SR.ID0025)),
// Both at+jwt and application/at+jwt are supported for access tokens.
JsonWebTokenTypes.AccessToken or JsonWebTokenTypes.Prefixes.Application + JsonWebTokenTypes.AccessToken
=> TokenTypeHints.AccessToken,
// Both JWT and application/JWT are supported for identity tokens.
JsonWebTokenTypes.IdentityToken or JsonWebTokenTypes.Prefixes.Application + JsonWebTokenTypes.IdentityToken
=> TokenTypeHints.IdToken,
JsonWebTokenTypes.Private.AuthorizationCode => TokenTypeHints.AuthorizationCode,
JsonWebTokenTypes.Private.DeviceCode => TokenTypeHints.DeviceCode,
JsonWebTokenTypes.Private.RefreshToken => TokenTypeHints.RefreshToken,
JsonWebTokenTypes.Private.UserCode => TokenTypeHints.UserCode,
_ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0003))
});
// Restore the claim destinations from the special oi_cl_dstn claim (represented as a dictionary/JSON object).
if (token.TryGetPayloadValue(Claims.Private.ClaimDestinationsMap, out ImmutableDictionary<string, string[]> destinations))
{
context.Principal.SetDestinations(destinations);
}
context.Logger.LogTrace(SR.GetResourceString(SR.ID6001), context.Token, context.Principal.Claims);
return default;
}
}
/// <summary>
/// Contains the logic responsible of normalizing the scope claims stored in the tokens.
/// </summary>
public class NormalizeScopeClaims : IOpenIddictServerHandler<ValidateTokenContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.UseSingletonHandler<NormalizeScopeClaims>()
.SetOrder(ValidateIdentityModelToken.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Principal is null)
{
return default;
}
// Note: in previous OpenIddict versions, scopes were represented as a JSON array
// and deserialized as multiple claims. In OpenIddict 3.0, the public "scope" claim
// is formatted as a unique space-separated string containing all the granted scopes.
// To ensure access tokens generated by previous versions are still correctly handled,
// both formats (unique space-separated string or multiple scope claims) must be supported.
// To achieve that, all the "scope" claims are combined into a single one containg all the values.
// Visit https://tools.ietf.org/html/draft-ietf-oauth-access-token-jwt-04 for more information.
var scopes = context.Principal.GetClaims(Claims.Scope);
if (scopes.Length > 1)
{
context.Principal.SetClaim(Claims.Scope, string.Join(" ", scopes));
}
return default;
}
}
/// <summary>
/// Contains the logic responsible of mapping internal claims used by OpenIddict.
/// </summary>
public class MapInternalClaims : IOpenIddictServerHandler<ValidateTokenContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.UseSingletonHandler<MapInternalClaims>()
.SetOrder(NormalizeScopeClaims.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Principal is null)
{
return default;
}
// To reduce the size of tokens, some of the private claims used by OpenIddict
// are mapped to their standard equivalent before being removed from the token.
// This handler is responsible of adding back the private claims to the principal
// when receiving the token (e.g "oi_prst" is resolved from the "scope" claim).
// In OpenIddict 3.0, the creation date of a token is stored in "oi_crt_dt".
// If the claim doesn't exist, try to infer it from the standard "iat" JWT claim.
if (!context.Principal.HasClaim(Claims.Private.CreationDate))
{
var date = context.Principal.GetClaim(Claims.IssuedAt);
if (!string.IsNullOrEmpty(date) &&
long.TryParse(date, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
context.Principal.SetCreationDate(DateTimeOffset.FromUnixTimeSeconds(value));
}
}
// In OpenIddict 3.0, the expiration date of a token is stored in "oi_exp_dt".
// If the claim doesn't exist, try to infer it from the standard "exp" JWT claim.
if (!context.Principal.HasClaim(Claims.Private.ExpirationDate))
{
var date = context.Principal.GetClaim(Claims.ExpiresAt);
if (!string.IsNullOrEmpty(date) &&
long.TryParse(date, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
context.Principal.SetExpirationDate(DateTimeOffset.FromUnixTimeSeconds(value));
}
}
// In OpenIddict 3.0, the audiences allowed to receive a token are stored in "oi_aud".
// If no such claim exists, try to infer them from the standard "aud" JWT claims.
if (!context.Principal.HasClaim(Claims.Private.Audience))
{
var audiences = context.Principal.GetClaims(Claims.Audience);
if (audiences.Any())
{
context.Principal.SetAudiences(audiences);
}
}
// In OpenIddict 3.0, the presenters allowed to use a token are stored in "oi_prst".
// If no such claim exists, try to infer them from the standard "azp" and "client_id" JWT claims.
//
// Note: in previous OpenIddict versions, the presenters were represented in JWT tokens
// using the "azp" claim (defined by OpenID Connect), for which a single value could be
// specified. To ensure presenters stored in JWT tokens created by OpenIddict 1.x/2.x
// can still be read with OpenIddict 3.0, the presenter is automatically inferred from
// the "azp" or "client_id" claim if no "oi_prst" claim was found in the principal.
if (!context.Principal.HasClaim(Claims.Private.Presenter))
{
var presenter = context.Principal.GetClaim(Claims.AuthorizedParty) ??
context.Principal.GetClaim(Claims.ClientId);
if (!string.IsNullOrEmpty(presenter))
{
context.Principal.SetPresenters(presenter);
}
}
// In OpenIddict 3.0, the scopes granted to an application are stored in "oi_scp".
// If no such claim exists, try to infer them from the standard "scope" JWT claim,
// which is guaranteed to be a unique space-separated claim containing all the values.
if (!context.Principal.HasClaim(Claims.Private.Scope))
{
var scope = context.Principal.GetClaim(Claims.Scope);
if (!string.IsNullOrEmpty(scope))
{
context.Principal.SetScopes(scope.Split(Separators.Space, StringSplitOptions.RemoveEmptyEntries));
}
}
return default;
}
}
/// <summary>
/// Contains the logic responsible of restoring the properties associated with a reference token entry.
/// Note: this handler is not used when the degraded mode is enabled.
/// </summary>
public class RestoreReferenceTokenProperties : IOpenIddictServerHandler<ValidateTokenContext>
{
private readonly IOpenIddictTokenManager _tokenManager;
public RestoreReferenceTokenProperties() => throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
public RestoreReferenceTokenProperties(IOpenIddictTokenManager tokenManager)
=> _tokenManager = tokenManager;
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.AddFilter<RequireDegradedModeDisabled>()
.AddFilter<RequireTokenStorageEnabled>()
.UseScopedHandler<RestoreReferenceTokenProperties>()
.SetOrder(MapInternalClaims.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
public async ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Principal is null || string.IsNullOrEmpty(context.TokenId))
{
return;
}
var token = await _tokenManager.FindByIdAsync(context.TokenId);
if (token is null)
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0021));
}
// Restore the creation/expiration dates/identifiers from the token entry metadata.
context.Principal.SetCreationDate(await _tokenManager.GetCreationDateAsync(token))
.SetExpirationDate(await _tokenManager.GetExpirationDateAsync(token))
.SetAuthorizationId(await _tokenManager.GetAuthorizationIdAsync(token))
.SetTokenId(await _tokenManager.GetIdAsync(token))
.SetTokenType(await _tokenManager.GetTypeAsync(token));
}
}
/// <summary>
/// Contains the logic responsible of rejecting authentication demands for which no valid principal was resolved.
/// </summary>
public class ValidatePrincipal : IOpenIddictServerHandler<ValidateTokenContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.UseSingletonHandler<ValidatePrincipal>()
.SetOrder(RestoreReferenceTokenProperties.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Principal is null)
{
context.Reject(
error: Errors.InvalidToken,
description: context.ValidTokenTypes.Count switch
{
1 when context.ValidTokenTypes.Contains(TokenTypeHints.AuthorizationCode)
=> SR.GetResourceString(SR.ID2001),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.DeviceCode)
=> SR.GetResourceString(SR.ID2002),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.RefreshToken)
=> SR.GetResourceString(SR.ID2003),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.IdToken)
=> SR.GetResourceString(SR.ID2009),
_ => SR.GetResourceString(SR.ID2004)
},
uri: context.ValidTokenTypes.Count switch
{
1 when context.ValidTokenTypes.Contains(TokenTypeHints.AuthorizationCode)
=> SR.FormatID8000(SR.ID2001),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.DeviceCode)
=> SR.FormatID8000(SR.ID2002),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.RefreshToken)
=> SR.FormatID8000(SR.ID2003),
1 when context.ValidTokenTypes.Contains(TokenTypeHints.IdToken)
=> SR.FormatID8000(SR.ID2009),
_ => SR.FormatID8000(SR.ID2004)
});
return default;
}
// When using JWT or Data Protection tokens, the correct token type is always enforced by IdentityModel
// (using the "typ" header) or by ASP.NET Core Data Protection (using per-token-type purposes strings).
// To ensure tokens deserialized using a custom routine are of the expected type, a manual check is used,
// which requires that a special claim containing the token type be present in the security principal.
var type = context.Principal.GetTokenType();
if (string.IsNullOrEmpty(type))
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0004));
}
if (context.ValidTokenTypes.Count > 0 && !context.ValidTokenTypes.Contains(type))
{
throw new InvalidOperationException(SR.FormatID0005(type, string.Join(", ", context.ValidTokenTypes)));
}
return default;
}
}
/// <summary>
/// Contains the logic responsible of rejecting authentication demands that use an expired token.
/// </summary>
public class ValidateExpirationDate : IOpenIddictServerHandler<ValidateTokenContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.AddFilter<RequireTokenLifetimeValidationEnabled>()
.UseSingletonHandler<ValidateExpirationDate>()
.SetOrder(ValidatePrincipal.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
var date = context.Principal.GetExpirationDate();
if (date.HasValue && date.Value < DateTimeOffset.UtcNow)
{
context.Reject(
error: context.Principal.GetTokenType() switch
{
TokenTypeHints.DeviceCode => Errors.ExpiredToken,
_ => Errors.InvalidToken
},
description: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.GetResourceString(SR.ID2016),
TokenTypeHints.DeviceCode => SR.GetResourceString(SR.ID2017),
TokenTypeHints.RefreshToken => SR.GetResourceString(SR.ID2018),
_ => SR.GetResourceString(SR.ID2019)
},
uri: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.FormatID8000(SR.ID2016),
TokenTypeHints.DeviceCode => SR.FormatID8000(SR.ID2017),
TokenTypeHints.RefreshToken => SR.FormatID8000(SR.ID2018),
_ => SR.FormatID8000(SR.ID2019)
});
return default;
}
return default;
}
}
/// <summary>
/// Contains the logic responsible of rejecting authentication demands that
/// use a token whose entry is no longer valid (e.g was revoked).
/// Note: this handler is not used when the degraded mode is enabled.
/// </summary>
public class ValidateTokenEntry : IOpenIddictServerHandler<ValidateTokenContext>
{
private readonly IOpenIddictTokenManager _tokenManager;
public ValidateTokenEntry() => throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
public ValidateTokenEntry(IOpenIddictTokenManager tokenManager)
=> _tokenManager = tokenManager;
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.AddFilter<RequireDegradedModeDisabled>()
.AddFilter<RequireTokenStorageEnabled>()
.UseScopedHandler<ValidateTokenEntry>()
.SetOrder(ValidateExpirationDate.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
public async ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
// Extract the token identifier from the authentication principal.
// If no token identifier can be found, this indicates that the token
// has no backing database entry (e.g an access token or an identity token).
var identifier = context.Principal.GetTokenId();
if (string.IsNullOrEmpty(identifier))
{
return;
}
// If the token entry cannot be found, return a generic error.
var token = await _tokenManager.FindByIdAsync(identifier);
if (token is null)
{
context.Reject(
error: Errors.InvalidToken,
description: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.GetResourceString(SR.ID2001),
TokenTypeHints.DeviceCode => SR.GetResourceString(SR.ID2002),
TokenTypeHints.RefreshToken => SR.GetResourceString(SR.ID2003),
_ => SR.GetResourceString(SR.ID2004)
},
uri: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.FormatID8000(SR.ID2001),
TokenTypeHints.DeviceCode => SR.FormatID8000(SR.ID2002),
TokenTypeHints.RefreshToken => SR.FormatID8000(SR.ID2003),
_ => SR.FormatID8000(SR.ID2004)
});
return;
}
// If the token is already marked as redeemed, this may indicate that it was compromised.
// In this case, revoke the entire chain of tokens associated with the authorization.
// Special logic is used to avoid revoking refresh tokens already marked as redeemed to allow for a small leeway.
// Note: the authorization itself is not revoked to allow the legitimate client to start a new flow.
// See https://tools.ietf.org/html/rfc6749#section-10.5 for more information.
if (await _tokenManager.HasStatusAsync(token, Statuses.Redeemed))
{
if (!context.Principal.HasTokenType(TokenTypeHints.RefreshToken) || !await IsReusableAsync(token))
{
context.Logger.LogInformation(SR.GetResourceString(SR.ID6002), identifier);
context.Reject(
error: Errors.InvalidToken,
description: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.GetResourceString(SR.ID2010),
TokenTypeHints.DeviceCode => SR.GetResourceString(SR.ID2011),
TokenTypeHints.RefreshToken => SR.GetResourceString(SR.ID2012),
_ => SR.GetResourceString(SR.ID2013)
},
uri: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.FormatID8000(SR.ID2010),
TokenTypeHints.DeviceCode => SR.FormatID8000(SR.ID2011),
TokenTypeHints.RefreshToken => SR.FormatID8000(SR.ID2012),
_ => SR.FormatID8000(SR.ID2013)
});
// Revoke all the token entries associated with the authorization.
await TryRevokeChainAsync(await _tokenManager.GetAuthorizationIdAsync(token));
return;
}
return;
}
// If the token is not marked as valid yet, return an authorization_pending error.
if (await _tokenManager.HasStatusAsync(token, Statuses.Inactive))
{
context.Logger.LogInformation(SR.GetResourceString(SR.ID6003), identifier);
context.Reject(
error: Errors.AuthorizationPending,
description: SR.GetResourceString(SR.ID2014),
uri: SR.FormatID8000(SR.ID2014));
return;
}
// If the token is marked as rejected, return an access_denied error.
if (await _tokenManager.HasStatusAsync(token, Statuses.Rejected))
{
context.Logger.LogInformation(SR.GetResourceString(SR.ID6004), identifier);
context.Reject(
error: Errors.AccessDenied,
description: SR.GetResourceString(SR.ID2015),
uri: SR.FormatID8000(SR.ID2015));
return;
}
if (!await _tokenManager.HasStatusAsync(token, Statuses.Valid))
{
context.Logger.LogInformation(SR.GetResourceString(SR.ID6005), identifier);
context.Reject(
error: Errors.InvalidToken,
description: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.GetResourceString(SR.ID2016),
TokenTypeHints.DeviceCode => SR.GetResourceString(SR.ID2017),
TokenTypeHints.RefreshToken => SR.GetResourceString(SR.ID2018),
_ => SR.GetResourceString(SR.ID2019)
},
uri: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.FormatID8000(SR.ID2016),
TokenTypeHints.DeviceCode => SR.FormatID8000(SR.ID2017),
TokenTypeHints.RefreshToken => SR.FormatID8000(SR.ID2018),
_ => SR.FormatID8000(SR.ID2019)
});
return;
}
// Restore the creation/expiration dates/identifiers from the token entry metadata.
context.Principal.SetCreationDate(await _tokenManager.GetCreationDateAsync(token))
.SetExpirationDate(await _tokenManager.GetExpirationDateAsync(token))
.SetAuthorizationId(await _tokenManager.GetAuthorizationIdAsync(token))
.SetTokenId(await _tokenManager.GetIdAsync(token))
.SetTokenType(await _tokenManager.GetTypeAsync(token));
async ValueTask<bool> IsReusableAsync(object token)
{
// If the reuse leeway was set to null, return false to indicate
// that the refresh token is already redeemed and cannot be reused.
if (context.Options.RefreshTokenReuseLeeway is null)
{
return false;
}
var date = await _tokenManager.GetRedemptionDateAsync(token);
if (date is null || DateTimeOffset.UtcNow < date + context.Options.RefreshTokenReuseLeeway)
{
return true;
}
return false;
}
async ValueTask TryRevokeChainAsync(string? identifier)
{
if (string.IsNullOrEmpty(identifier))
{
return;
}
// Revoke all the token entries associated with the authorization,
// including the redeemed token that was used in the token request.
await foreach (var token in _tokenManager.FindByAuthorizationIdAsync(identifier))
{
await _tokenManager.TryRevokeAsync(token);
}
}
}
}
/// <summary>
/// Contains the logic responsible of authentication demands a token whose
/// associated authorization entry is no longer valid (e.g was revoked).
/// Note: this handler is not used when the degraded mode is enabled.
/// </summary>
public class ValidateAuthorizationEntry : IOpenIddictServerHandler<ValidateTokenContext>
{
private readonly IOpenIddictAuthorizationManager _authorizationManager;
public ValidateAuthorizationEntry() => throw new InvalidOperationException(SR.GetResourceString(SR.ID0016));
public ValidateAuthorizationEntry(IOpenIddictAuthorizationManager authorizationManager)
=> _authorizationManager = authorizationManager;
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.AddFilter<RequireDegradedModeDisabled>()
.AddFilter<RequireAuthorizationStorageEnabled>()
.UseScopedHandler<ValidateAuthorizationEntry>()
.SetOrder(ValidateTokenEntry.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
public async ValueTask HandleAsync(ValidateTokenContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
Debug.Assert(context.Principal is { Identity: ClaimsIdentity }, SR.GetResourceString(SR.ID4006));
var identifier = context.Principal.GetAuthorizationId();
if (string.IsNullOrEmpty(identifier))
{
return;
}
var authorization = await _authorizationManager.FindByIdAsync(identifier);
if (authorization is null || !await _authorizationManager.HasStatusAsync(authorization, Statuses.Valid))
{
context.Logger.LogInformation(SR.GetResourceString(SR.ID6006), identifier);
context.Reject(
error: Errors.InvalidToken,
description: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.GetResourceString(SR.ID2020),
TokenTypeHints.DeviceCode => SR.GetResourceString(SR.ID2021),
TokenTypeHints.RefreshToken => SR.GetResourceString(SR.ID2022),
_ => SR.GetResourceString(SR.ID2023)
},
uri: context.Principal.GetTokenType() switch
{
TokenTypeHints.AuthorizationCode => SR.FormatID8000(SR.ID2020),
TokenTypeHints.DeviceCode => SR.FormatID8000(SR.ID2021),
TokenTypeHints.RefreshToken => SR.FormatID8000(SR.ID2022),
_ => SR.FormatID8000(SR.ID2023)
});
return;
}