-
Notifications
You must be signed in to change notification settings - Fork 401
/
JwtSecurityTokenHandler.cs
1921 lines (1706 loc) · 108 KB
/
JwtSecurityTokenHandler.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.IdentityModel.Abstractions;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
namespace System.IdentityModel.Tokens.Jwt
{
/// <summary>
/// A <see cref="SecurityTokenHandler"/> designed for creating and validating Json Web Tokens. See: https://datatracker.ietf.org/doc/html/rfc7519 and http://www.rfc-editor.org/info/rfc7515
/// </summary>
public class JwtSecurityTokenHandler : SecurityTokenHandler
{
private delegate bool CertMatcher(X509Certificate2 cert);
private ISet<string> _inboundClaimFilter;
private IDictionary<string, string> _inboundClaimTypeMap;
private static string _jsonClaimType = _namespace + "/json_type";
private const string _namespace = "http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties";
private const string _className = "System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler";
private IDictionary<string, string> _outboundClaimTypeMap;
private Dictionary<string, string> _outboundAlgorithmMap;
private static string _shortClaimType = _namespace + "/ShortTypeName";
private bool _mapInboundClaims = DefaultMapInboundClaims;
/// <summary>
/// Default claim type mapping for inbound claims.
/// </summary>
public static IDictionary<string, string> DefaultInboundClaimTypeMap = new Dictionary<string, string>(ClaimTypeMapping.InboundClaimTypeMap);
/// <summary>
/// Default value for the flag that determines whether or not the InboundClaimTypeMap is used.
/// </summary>
public static bool DefaultMapInboundClaims = true;
/// <summary>
/// Default claim type mapping for outbound claims.
/// </summary>
public static IDictionary<string, string> DefaultOutboundClaimTypeMap = new Dictionary<string, string>(ClaimTypeMapping.OutboundClaimTypeMap);
/// <summary>
/// Default claim type filter list.
/// </summary>
public static ISet<string> DefaultInboundClaimFilter = ClaimTypeMapping.InboundClaimFilter;
/// <summary>
/// Default JwtHeader algorithm mapping
/// </summary>
public static IDictionary<string, string> DefaultOutboundAlgorithmMap = new Dictionary<string, string>
{
{ SecurityAlgorithms.EcdsaSha256Signature, SecurityAlgorithms.EcdsaSha256 },
{ SecurityAlgorithms.EcdsaSha384Signature, SecurityAlgorithms.EcdsaSha384 },
{ SecurityAlgorithms.EcdsaSha512Signature, SecurityAlgorithms.EcdsaSha512 },
{ SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.HmacSha256 },
{ SecurityAlgorithms.HmacSha384Signature, SecurityAlgorithms.HmacSha384 },
{ SecurityAlgorithms.HmacSha512Signature, SecurityAlgorithms.HmacSha512 },
{ SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.RsaSha256 },
{ SecurityAlgorithms.RsaSha384Signature, SecurityAlgorithms.RsaSha384 },
{ SecurityAlgorithms.RsaSha512Signature, SecurityAlgorithms.RsaSha512 },
};
/// <summary>
/// Static initializer for a new object. Static initializers run before the first instance of the type is created.
/// </summary>
static JwtSecurityTokenHandler()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JwtSecurityTokenHandler"/> class.
/// </summary>
public JwtSecurityTokenHandler()
{
if (_mapInboundClaims)
_inboundClaimTypeMap = new Dictionary<string, string>(DefaultInboundClaimTypeMap);
else
_inboundClaimTypeMap = new Dictionary<string, string>();
_outboundClaimTypeMap = new Dictionary<string, string>(DefaultOutboundClaimTypeMap);
_inboundClaimFilter = new HashSet<string>(DefaultInboundClaimFilter);
_outboundAlgorithmMap = new Dictionary<string, string>(DefaultOutboundAlgorithmMap);
}
/// <summary>
/// Gets or sets the <see cref="MapInboundClaims"/> property which is used when determining whether or not to map claim types that are extracted when validating a <see cref="JwtSecurityToken"/>.
/// <para>If this is set to true, the <see cref="Claim.Type"/> is set to the JSON claim 'name' after translating using this mapping. Otherwise, no mapping occurs.</para>
/// <para>The default value is true.</para>
/// </summary>
public bool MapInboundClaims
{
get
{
return _mapInboundClaims;
}
set
{
// If the inbound claim type mapping was turned off and is being turned on for the first time, make sure that the _inboundClaimTypeMap is populated with the default mappings.
if (!_mapInboundClaims && value && _inboundClaimTypeMap.Count == 0)
_inboundClaimTypeMap = new Dictionary<string, string>(DefaultInboundClaimTypeMap);
_mapInboundClaims = value;
}
}
/// <summary>
/// Gets or sets the <see cref="InboundClaimTypeMap"/> which is used when setting the <see cref="Claim.Type"/> for claims in the <see cref="ClaimsPrincipal"/> extracted when validating a <see cref="JwtSecurityToken"/>.
/// <para>The <see cref="Claim.Type"/> is set to the JSON claim 'name' after translating using this mapping.</para>
/// <para>The default value is ClaimTypeMapping.InboundClaimTypeMap.</para>
/// </summary>
/// <exception cref="ArgumentNullException">'value' is null.</exception>
public IDictionary<string, string> InboundClaimTypeMap
{
get
{
return _inboundClaimTypeMap;
}
set
{
_inboundClaimTypeMap = value ?? throw LogHelper.LogArgumentNullException(nameof(value));
}
}
/// <summary>
/// <para>Gets or sets the <see cref="OutboundClaimTypeMap"/> which is used when creating a <see cref="JwtSecurityToken"/> from <see cref="Claim"/>(s).</para>
/// <para>The JSON claim 'name' value is set to <see cref="Claim.Type"/> after translating using this mapping.</para>
/// <para>The default value is ClaimTypeMapping.OutboundClaimTypeMap</para>
/// </summary>
/// <remarks>This mapping is applied only when using <see cref="JwtPayload.AddClaim"/> or <see cref="JwtPayload.AddClaims"/>. Adding values directly will not result in translation.</remarks>
/// <exception cref="ArgumentNullException">'value' is null.</exception>
public IDictionary<string, string> OutboundClaimTypeMap
{
get
{
return _outboundClaimTypeMap;
}
set
{
if (value == null)
throw LogHelper.LogArgumentNullException(nameof(value));
_outboundClaimTypeMap = value;
}
}
/// <summary>
/// Gets the outbound algorithm map that is passed to the <see cref="JwtHeader"/> constructor.
/// </summary>
public IDictionary<string, string> OutboundAlgorithmMap
{
get
{
return _outboundAlgorithmMap;
}
}
/// <summary>Gets or sets the <see cref="ISet{String}"/> used to filter claims when populating a <see cref="ClaimsIdentity"/> claims form a <see cref="JwtSecurityToken"/>.
/// When a <see cref="JwtSecurityToken"/> is validated, claims with types found in this <see cref="ISet{String}"/> will not be added to the <see cref="ClaimsIdentity"/>.
/// <para>The default value is ClaimTypeMapping.InboundClaimFilter.</para>
/// </summary>
/// <exception cref="ArgumentNullException">'value' is null.</exception>
public ISet<string> InboundClaimFilter
{
get
{
return _inboundClaimFilter;
}
set
{
if (value == null)
throw LogHelper.LogArgumentNullException(nameof(value));
_inboundClaimFilter = value;
}
}
/// <summary>
/// Gets or sets the property name of <see cref="Claim.Properties"/> the will contain the original JSON claim 'name' if a mapping occurred when the <see cref="Claim"/>(s) were created.
/// <para>See <seealso cref="InboundClaimTypeMap"/> for more information.</para>
/// </summary>
/// <exception cref="ArgumentException">If <see cref="string"/>.IsNullOrWhiteSpace('value') is true.</exception>
public static string ShortClaimTypeProperty
{
get
{
return _shortClaimType;
}
set
{
if (string.IsNullOrWhiteSpace(value))
throw LogHelper.LogArgumentNullException(nameof(value));
_shortClaimType = value;
}
}
/// <summary>
/// Gets or sets the property name of <see cref="Claim.Properties"/> the will contain .Net type that was recognized when <see cref="JwtPayload.Claims"/> serialized the value to JSON.
/// <para>See <seealso cref="InboundClaimTypeMap"/> for more information.</para>
/// </summary>
/// <exception cref="ArgumentException">If <see cref="string"/>.IsNullOrWhiteSpace('value') is true.</exception>
public static string JsonClaimTypeProperty
{
get
{
return _jsonClaimType;
}
set
{
if (string.IsNullOrWhiteSpace(value))
throw LogHelper.LogArgumentNullException(nameof(value));
_jsonClaimType = value;
}
}
/// <summary>
/// Returns a value that indicates if this handler can validate a <see cref="SecurityToken"/>.
/// </summary>
/// <returns>'true', indicating this instance can validate a <see cref="JwtSecurityToken"/>.</returns>
public override bool CanValidateToken
{
get { return true; }
}
/// <summary>
/// Gets the value that indicates if this instance can write a <see cref="SecurityToken"/>.
/// </summary>
/// <returns>'true', indicating this instance can write a <see cref="JwtSecurityToken"/>.</returns>
public override bool CanWriteToken
{
get { return true; }
}
/// <summary>
/// Gets the type of the <see cref="JwtSecurityToken"/>.
/// </summary>
/// <return>The type of <see cref="JwtSecurityToken"/></return>
public override Type TokenType
{
get { return typeof(JwtSecurityToken); }
}
/// <summary>
/// Determines if the string is a well formed Json Web Token (JWT).
/// <para>See: https://datatracker.ietf.org/doc/html/rfc7519 </para>
/// </summary>
/// <param name="token">String that should represent a valid JWT.</param>
/// <remarks>Uses <see cref="Regex.IsMatch(string, string)"/> matching one of:
/// <para>JWS: @"^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$"</para>
/// <para>JWE: (dir): @"^[A-Za-z0-9-_]+\.\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$"</para>
/// <para>JWE: (wrappedkey): @"^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]$"</para>
/// </remarks>
/// <returns>
/// <para>'false' if the token is null or whitespace.</para>
/// <para>'false' if token.Length is greater than <see cref="TokenHandler.MaximumTokenSizeInBytes"/>.</para>
/// <para>'true' if the token is in JSON compact serialization format.</para>
/// </returns>
public override bool CanReadToken(string token)
{
if (string.IsNullOrWhiteSpace(token))
return false;
if (token.Length > MaximumTokenSizeInBytes)
{
if (LogHelper.IsEnabled(EventLogLevel.Informational))
LogHelper.LogInformation(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes));
return false;
}
// Set the maximum number of segments to MaxJwtSegmentCount + 1. This controls the number of splits and allows detecting the number of segments is too large.
// For example: "a.b.c.d.e.f.g.h" => [a], [b], [c], [d], [e], [f.g.h]. 6 segments.
// If just MaxJwtSegmentCount was used, then [a], [b], [c], [d], [e.f.g.h] would be returned. 5 segments.
int tokenPartCount = JwtTokenUtilities.CountJwtTokenPart(token, JwtConstants.MaxJwtSegmentCount + 1);
if (tokenPartCount == JwtConstants.JwsSegmentCount)
{
return JwtTokenUtilities.RegexJws.IsMatch(token);
}
else if (tokenPartCount == JwtConstants.JweSegmentCount)
{
return JwtTokenUtilities.RegexJwe.IsMatch(token);
}
LogHelper.LogInformation(LogMessages.IDX12720);
return false;
}
/// <summary>
/// Returns a Json Web Token (JWT).
/// </summary>
/// <param name="tokenDescriptor">A <see cref="SecurityTokenDescriptor"/> that contains details of contents of the token.</param>
/// <remarks>A JWS and JWE can be returned.
/// <para>If <see cref="SecurityTokenDescriptor.EncryptingCredentials"/>is provided, then a JWE will be created.</para>
/// <para>If <see cref="SecurityTokenDescriptor.SigningCredentials"/> is provided then a JWS will be created.</para>
/// <para>If both are provided then a JWE with an embedded JWS will be created.</para>
/// </remarks>
public virtual string CreateEncodedJwt(SecurityTokenDescriptor tokenDescriptor)
{
if (tokenDescriptor == null)
throw LogHelper.LogArgumentNullException(nameof(tokenDescriptor));
return CreateJwtSecurityToken(tokenDescriptor).RawData;
}
/// <summary>
/// Creates a JWT in 'Compact Serialization Format'.
/// </summary>
/// <param name="issuer">The issuer of the token.</param>
/// <param name="audience">The audience for this token.</param>
/// <param name="subject">The source of the <see cref="Claim"/>(s) for this token.</param>
/// <param name="notBefore">The notbefore time for this token.</param>
/// <param name="expires">The expiration time for this token.</param>
/// <param name="issuedAt">The issue time for this token.</param>
/// <param name="signingCredentials">Contains cryptographic material for generating a signature.</param>
/// <remarks>If <see cref="ClaimsIdentity.Actor"/> is not null, then a claim { actort, 'value' } will be added to the payload. See <see cref="CreateActorValue"/> for details on how the value is created.
/// <para>See <seealso cref="JwtHeader"/> for details on how the HeaderParameters are added to the header.</para>
/// <para>See <seealso cref="JwtPayload"/> for details on how the values are added to the payload.</para>
/// <para>Each <see cref="Claim"/> in the <paramref name="subject"/> will map <see cref="Claim.Type"/> by applying <see cref="OutboundClaimTypeMap"/>. Modifying <see cref="OutboundClaimTypeMap"/> could change the outbound JWT.</para>
/// <para>If <see cref="SigningCredentials"/> is provided, then a JWS will be created.</para>
/// </remarks>
/// <returns>A Base64UrlEncoded string in 'Compact Serialization Format'.</returns>
public virtual string CreateEncodedJwt(
string issuer,
string audience,
ClaimsIdentity subject,
DateTime? notBefore,
DateTime? expires,
DateTime? issuedAt,
SigningCredentials signingCredentials) => CreateJwtSecurityTokenPrivate(new SecurityTokenDescriptor
{
Issuer = issuer,
Audience = audience,
Subject = subject,
NotBefore = notBefore,
Expires = expires,
IssuedAt = issuedAt,
SigningCredentials = signingCredentials
}).RawData;
/// <summary>
/// Creates a JWT in 'Compact Serialization Format'.
/// </summary>
/// <param name="issuer">The issuer of the token.</param>
/// <param name="audience">The audience for this token.</param>
/// <param name="subject">The source of the <see cref="Claim"/>(s) for this token.</param>
/// <param name="notBefore">Translated into 'epoch time' and assigned to 'nbf'.</param>
/// <param name="expires">Translated into 'epoch time' and assigned to 'exp'.</param>
/// <param name="issuedAt">Translated into 'epoch time' and assigned to 'iat'.</param>
/// <param name="signingCredentials">Contains cryptographic material for signing.</param>
/// <param name="encryptingCredentials">Contains cryptographic material for encrypting.</param>
/// <remarks>If <see cref="ClaimsIdentity.Actor"/> is not null, then a claim { actort, 'value' } will be added to the payload. <see cref="CreateActorValue"/> for details on how the value is created.
/// <para>See <seealso cref="JwtHeader"/> for details on how the HeaderParameters are added to the header.</para>
/// <para>See <seealso cref="JwtPayload"/> for details on how the values are added to the payload.</para>
/// <para>Each <see cref="Claim"/> in the <paramref name="subject"/> will map <see cref="Claim.Type"/> by applying <see cref="OutboundClaimTypeMap"/>. Modifying <see cref="OutboundClaimTypeMap"/> could change the outbound JWT.</para>
/// </remarks>
/// <returns>A Base64UrlEncoded string in 'Compact Serialization Format'.</returns>
/// <exception cref="ArgumentException">If 'expires' <= 'notBefore'.</exception>
public virtual string CreateEncodedJwt(
string issuer,
string audience,
ClaimsIdentity subject,
DateTime? notBefore,
DateTime? expires,
DateTime? issuedAt,
SigningCredentials signingCredentials,
EncryptingCredentials encryptingCredentials) => CreateJwtSecurityTokenPrivate(new SecurityTokenDescriptor
{
Issuer = issuer,
Audience = audience,
Subject = subject,
NotBefore = notBefore,
Expires = expires,
IssuedAt = issuedAt,
SigningCredentials = signingCredentials,
EncryptingCredentials = encryptingCredentials
}).RawData;
/// <summary>
/// Creates a JWT in 'Compact Serialization Format'.
/// </summary>
/// <param name="issuer">The issuer of the token.</param>
/// <param name="audience">The audience for this token.</param>
/// <param name="subject">The source of the <see cref="Claim"/>(s) for this token.</param>
/// <param name="notBefore">Translated into 'epoch time' and assigned to 'nbf'.</param>
/// <param name="expires">Translated into 'epoch time' and assigned to 'exp'.</param>
/// <param name="issuedAt">Translated into 'epoch time' and assigned to 'iat'.</param>
/// <param name="signingCredentials">Contains cryptographic material for signing.</param>
/// <param name="encryptingCredentials">Contains cryptographic material for encrypting.</param>
/// <param name="claimCollection">A collection of (key,value) pairs representing <see cref="Claim"/>(s) for this token.</param>
/// <remarks>If <see cref="ClaimsIdentity.Actor"/> is not null, then a claim { actort, 'value' } will be added to the payload. <see cref="CreateActorValue"/> for details on how the value is created.
/// <para>See <seealso cref="JwtHeader"/> for details on how the HeaderParameters are added to the header.</para>
/// <para>See <seealso cref="JwtPayload"/> for details on how the values are added to the payload.</para>
/// <para>Each <see cref="Claim"/> in the <paramref name="subject"/> will map <see cref="Claim.Type"/> by applying <see cref="OutboundClaimTypeMap"/>. Modifying <see cref="OutboundClaimTypeMap"/> could change the outbound JWT.</para>
/// </remarks>
/// <returns>A Base64UrlEncoded string in 'Compact Serialization Format'.</returns>
/// <exception cref="ArgumentException">If 'expires' <= 'notBefore'.</exception>
public virtual string CreateEncodedJwt(
string issuer,
string audience,
ClaimsIdentity subject,
DateTime? notBefore,
DateTime? expires,
DateTime? issuedAt,
SigningCredentials signingCredentials,
EncryptingCredentials encryptingCredentials,
IDictionary<string, object> claimCollection) => CreateJwtSecurityTokenPrivate(new SecurityTokenDescriptor
{
Issuer = issuer,
Audience = audience,
Subject = subject,
NotBefore = notBefore,
Expires = expires,
IssuedAt = issuedAt,
SigningCredentials = signingCredentials,
EncryptingCredentials = encryptingCredentials,
Claims = claimCollection
}).RawData;
/// <summary>
/// Creates a Json Web Token (JWT).
/// </summary>
/// <param name="tokenDescriptor"> A <see cref="SecurityTokenDescriptor"/> that contains details of contents of the token.</param>
/// <remarks><see cref="SecurityTokenDescriptor.SigningCredentials"/> is used to sign <see cref="JwtSecurityToken.RawData"/>.</remarks>
public virtual JwtSecurityToken CreateJwtSecurityToken(SecurityTokenDescriptor tokenDescriptor)
{
if (tokenDescriptor == null)
throw LogHelper.LogArgumentNullException(nameof(tokenDescriptor));
return CreateJwtSecurityTokenPrivate(tokenDescriptor);
}
/// <summary>
/// Creates a <see cref="JwtSecurityToken"/>
/// </summary>
/// <param name="issuer">The issuer of the token.</param>
/// <param name="audience">The audience for this token.</param>
/// <param name="subject">The source of the <see cref="Claim"/>(s) for this token.</param>
/// <param name="notBefore">The notbefore time for this token.</param>
/// <param name="expires">The expiration time for this token.</param>
/// <param name="issuedAt">The issue time for this token.</param>
/// <param name="signingCredentials">Contains cryptographic material for generating a signature.</param>
/// <param name="encryptingCredentials">Contains cryptographic material for encrypting the token.</param>
/// <remarks>If <see cref="ClaimsIdentity.Actor"/> is not null, then a claim { actort, 'value' } will be added to the payload. <see cref="CreateActorValue"/> for details on how the value is created.
/// <para>See <seealso cref="JwtHeader"/> for details on how the HeaderParameters are added to the header.</para>
/// <para>See <seealso cref="JwtPayload"/> for details on how the values are added to the payload.</para>
/// <para>Each <see cref="Claim"/> on the <paramref name="subject"/> added will have <see cref="Claim.Type"/> translated according to the mapping found in
/// <see cref="OutboundClaimTypeMap"/>. Adding and removing to <see cref="OutboundClaimTypeMap"/> will affect the name component of the Json claim.</para>
/// <para><see cref="SigningCredentials.SigningCredentials(SecurityKey, string)"/> is used to sign <see cref="JwtSecurityToken.RawData"/>.</para>
/// <para><see cref="EncryptingCredentials.EncryptingCredentials(SecurityKey, string, string)"/> is used to encrypt <see cref="JwtSecurityToken.RawData"/> or <see cref="JwtSecurityToken.RawPayload"/> .</para>
/// </remarks>
/// <returns>A <see cref="JwtSecurityToken"/>.</returns>
/// <exception cref="ArgumentException">If <paramref name="expires"/> <= <paramref name="notBefore"/>.</exception>
public virtual JwtSecurityToken CreateJwtSecurityToken(
string issuer,
string audience,
ClaimsIdentity subject,
DateTime? notBefore,
DateTime? expires,
DateTime? issuedAt,
SigningCredentials signingCredentials,
EncryptingCredentials encryptingCredentials) => CreateJwtSecurityTokenPrivate(new SecurityTokenDescriptor
{
Issuer = issuer,
Audience = audience,
Subject = subject,
NotBefore = notBefore,
Expires = expires,
IssuedAt = issuedAt,
SigningCredentials = signingCredentials,
EncryptingCredentials = encryptingCredentials
});
/// <summary>
/// Creates a <see cref="JwtSecurityToken"/>
/// </summary>
/// <param name="issuer">The issuer of the token.</param>
/// <param name="audience">The audience for this token.</param>
/// <param name="subject">The source of the <see cref="Claim"/>(s) for this token.</param>
/// <param name="notBefore">The notbefore time for this token.</param>
/// <param name="expires">The expiration time for this token.</param>
/// <param name="issuedAt">The issue time for this token.</param>
/// <param name="signingCredentials">Contains cryptographic material for generating a signature.</param>
/// <param name="encryptingCredentials">Contains cryptographic material for encrypting the token.</param>
/// <param name="claimCollection">A collection of (key,value) pairs representing <see cref="Claim"/>(s) for this token.</param>
/// <remarks>If <see cref="ClaimsIdentity.Actor"/> is not null, then a claim { actort, 'value' } will be added to the payload. <see cref="CreateActorValue"/> for details on how the value is created.
/// <para>See <seealso cref="JwtHeader"/> for details on how the HeaderParameters are added to the header.</para>
/// <para>See <seealso cref="JwtPayload"/> for details on how the values are added to the payload.</para>
/// <para>Each <see cref="Claim"/> on the <paramref name="subject"/> added will have <see cref="Claim.Type"/> translated according to the mapping found in
/// <see cref="OutboundClaimTypeMap"/>. Adding and removing to <see cref="OutboundClaimTypeMap"/> will affect the name component of the Json claim.</para>
/// <para><see cref="SigningCredentials.SigningCredentials(SecurityKey, string)"/> is used to sign <see cref="JwtSecurityToken.RawData"/>.</para>
/// <para><see cref="EncryptingCredentials.EncryptingCredentials(SecurityKey, string, string)"/> is used to encrypt <see cref="JwtSecurityToken.RawData"/> or <see cref="JwtSecurityToken.RawPayload"/> .</para>
/// </remarks>
/// <returns>A <see cref="JwtSecurityToken"/>.</returns>
/// <exception cref="ArgumentException">If <paramref name="expires"/> <= <paramref name="notBefore"/>.</exception>
public virtual JwtSecurityToken CreateJwtSecurityToken(
string issuer,
string audience,
ClaimsIdentity subject,
DateTime? notBefore,
DateTime? expires,
DateTime? issuedAt,
SigningCredentials signingCredentials,
EncryptingCredentials encryptingCredentials,
IDictionary<string, object> claimCollection) => CreateJwtSecurityTokenPrivate(new SecurityTokenDescriptor
{
Issuer = issuer,
Audience = audience,
Subject = subject,
NotBefore = notBefore,
Expires = expires,
IssuedAt = issuedAt,
SigningCredentials = signingCredentials,
EncryptingCredentials = encryptingCredentials,
Claims = claimCollection
});
/// <summary>
/// Creates a <see cref="JwtSecurityToken"/>
/// </summary>
/// <param name="issuer">The issuer of the token.</param>
/// <param name="audience">The audience for this token.</param>
/// <param name="subject">The source of the <see cref="Claim"/>(s) for this token.</param>
/// <param name="notBefore">The notbefore time for this token.</param>
/// <param name="expires">The expiration time for this token.</param>
/// <param name="issuedAt">The issue time for this token.</param>
/// <param name="signingCredentials">Contains cryptographic material for generating a signature.</param>
/// <remarks>If <see cref="ClaimsIdentity.Actor"/> is not null, then a claim { actort, 'value' } will be added to the payload. <see cref="CreateActorValue"/> for details on how the value is created.
/// <para>See <seealso cref="JwtHeader"/> for details on how the HeaderParameters are added to the header.</para>
/// <para>See <seealso cref="JwtPayload"/> for details on how the values are added to the payload.</para>
/// <para>Each <see cref="Claim"/> on the <paramref name="subject"/> added will have <see cref="Claim.Type"/> translated according to the mapping found in
/// <see cref="OutboundClaimTypeMap"/>. Adding and removing to <see cref="OutboundClaimTypeMap"/> will affect the name component of the Json claim.</para>
/// <para><see cref="SigningCredentials.SigningCredentials(SecurityKey, string)"/> is used to sign <see cref="JwtSecurityToken.RawData"/>.</para>
/// </remarks>
/// <returns>A <see cref="JwtSecurityToken"/>.</returns>
/// <exception cref="ArgumentException">If <paramref name="expires"/> <= <paramref name="notBefore"/>.</exception>
public virtual JwtSecurityToken CreateJwtSecurityToken(
string issuer = null,
string audience = null,
ClaimsIdentity subject = null,
DateTime? notBefore = null,
DateTime? expires = null,
DateTime? issuedAt = null,
SigningCredentials signingCredentials = null) => CreateJwtSecurityTokenPrivate(new SecurityTokenDescriptor
{
Issuer = issuer,
Audience = audience,
Subject = subject,
NotBefore = notBefore,
Expires = expires,
IssuedAt = issuedAt,
SigningCredentials = signingCredentials
});
/// <summary>
/// Creates a Json Web Token (JWT).
/// </summary>
/// <param name="tokenDescriptor"> A <see cref="SecurityTokenDescriptor"/> that contains details of contents of the token.</param>
/// <remarks><see cref="SecurityTokenDescriptor.SigningCredentials"/> is used to sign <see cref="JwtSecurityToken.RawData"/>.</remarks>
public override SecurityToken CreateToken(SecurityTokenDescriptor tokenDescriptor)
{
if (tokenDescriptor == null)
throw LogHelper.LogArgumentNullException(nameof(tokenDescriptor));
return CreateJwtSecurityTokenPrivate(tokenDescriptor);
}
private JwtSecurityToken CreateJwtSecurityTokenPrivate(SecurityTokenDescriptor tokenDescriptor)
{
DateTime? expires = tokenDescriptor.Expires;
DateTime? issuedAt = tokenDescriptor.IssuedAt;
DateTime? notBefore = tokenDescriptor.NotBefore;
if (SetDefaultTimesOnTokenCreation && (!expires.HasValue || !issuedAt.HasValue || !notBefore.HasValue))
{
DateTime now = DateTime.UtcNow;
if (!expires.HasValue)
expires = now + TimeSpan.FromMinutes(TokenLifetimeInMinutes);
if (!issuedAt.HasValue)
issuedAt = now;
if (!notBefore.HasValue)
notBefore = now;
}
string issuer = tokenDescriptor.Issuer;
ClaimsIdentity subject = tokenDescriptor.Subject;
IDictionary<string, object> claimCollection = tokenDescriptor.Claims;
JwtPayload payload = new JwtPayload(issuer, tokenDescriptor.Audience, tokenDescriptor.Audiences, (subject == null ? null : OutboundClaimTypeTransform(subject.Claims)), (claimCollection == null ? null : OutboundClaimTypeTransform(claimCollection)), notBefore, expires, issuedAt);
SigningCredentials signingCredentials = tokenDescriptor.SigningCredentials;
string tokenType = tokenDescriptor.TokenType;
JwtHeader header = new JwtHeader(signingCredentials, OutboundAlgorithmMap, tokenType, tokenDescriptor.AdditionalInnerHeaderClaims, tokenDescriptor.IncludeKeyIdInHeader);
if (LogHelper.IsEnabled(EventLogLevel.Verbose))
LogHelper.LogVerbose(LogMessages.IDX12721, LogHelper.MarkAsNonPII(issuer ?? "null"), LogHelper.MarkAsNonPII(payload.Aud.ToString() ?? "null"));
if (subject?.Actor != null)
payload.AddClaim(new Claim(JwtRegisteredClaimNames.Actort, CreateActorValue(subject.Actor)));
string rawHeader = header.Base64UrlEncode();
string rawPayload = payload.Base64UrlEncode();
string rawSignature = string.Empty;
if (signingCredentials != null)
{
string message = string.Concat(rawHeader, ".", rawPayload);
rawSignature = JwtTokenUtilities.CreateEncodedSignature(message, signingCredentials);
}
if (LogHelper.IsEnabled(EventLogLevel.Informational))
LogHelper.LogInformation(LogMessages.IDX12722, rawHeader, rawPayload);
EncryptingCredentials encryptingCredentials = tokenDescriptor.EncryptingCredentials;
if (encryptingCredentials != null)
{
return EncryptToken(
new JwtSecurityToken(header, payload, rawHeader, rawPayload, rawSignature),
encryptingCredentials,
tokenType,
tokenDescriptor.AdditionalHeaderClaims);
}
return new JwtSecurityToken(header, payload, rawHeader, rawPayload, rawSignature);
}
private JwtSecurityToken EncryptToken(
JwtSecurityToken innerJwt,
EncryptingCredentials encryptingCredentials,
string tokenType,
IDictionary<string, object> additionalHeaderClaims)
{
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
var cryptoProviderFactory = encryptingCredentials.CryptoProviderFactory ?? encryptingCredentials.Key.CryptoProviderFactory;
if (cryptoProviderFactory == null)
throw LogHelper.LogExceptionMessage(new ArgumentException(TokenLogMessages.IDX10620));
SecurityKey securityKey = JwtTokenUtilities.GetSecurityKey(encryptingCredentials, cryptoProviderFactory, additionalHeaderClaims, out byte[] wrappedKey);
using (AuthenticatedEncryptionProvider encryptionProvider = cryptoProviderFactory.CreateAuthenticatedEncryptionProvider(securityKey, encryptingCredentials.Enc))
{
if (encryptionProvider == null)
throw LogHelper.LogExceptionMessage(new SecurityTokenEncryptionFailedException(LogMessages.IDX12730));
try
{
var header = new JwtHeader(encryptingCredentials, OutboundAlgorithmMap, tokenType, additionalHeaderClaims);
var encodedHeader = header.Base64UrlEncode();
AuthenticatedEncryptionResult encryptionResult = encryptionProvider.Encrypt(Encoding.UTF8.GetBytes(innerJwt.RawData), Encoding.ASCII.GetBytes(encodedHeader));
return JwtConstants.DirectKeyUseAlg.Equals(encryptingCredentials.Alg) ?
new JwtSecurityToken(
header,
innerJwt,
encodedHeader,
string.Empty,
Base64UrlEncoder.Encode(encryptionResult.IV),
Base64UrlEncoder.Encode(encryptionResult.Ciphertext),
Base64UrlEncoder.Encode(encryptionResult.AuthenticationTag)) :
new JwtSecurityToken(
header,
innerJwt,
encodedHeader,
Base64UrlEncoder.Encode(wrappedKey),
Base64UrlEncoder.Encode(encryptionResult.IV),
Base64UrlEncoder.Encode(encryptionResult.Ciphertext),
Base64UrlEncoder.Encode(encryptionResult.AuthenticationTag));
}
catch (Exception ex)
{
throw LogHelper.LogExceptionMessage(new SecurityTokenEncryptionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10616, LogHelper.MarkAsNonPII(encryptingCredentials.Enc), encryptingCredentials.Key), ex));
}
}
}
private IEnumerable<Claim> OutboundClaimTypeTransform(IEnumerable<Claim> claims)
{
foreach (Claim claim in claims)
{
string type = null;
if (_outboundClaimTypeMap.TryGetValue(claim.Type, out type))
{
yield return new Claim(type, claim.Value, claim.ValueType, claim.Issuer, claim.OriginalIssuer, claim.Subject);
}
else
{
yield return claim;
}
}
}
private Dictionary<string, object> OutboundClaimTypeTransform(IDictionary<string, object> claimCollection)
{
var claims = new Dictionary<string, object>();
foreach (string claimType in claimCollection.Keys)
{
if (_outboundClaimTypeMap.TryGetValue(claimType, out string type))
claims[type] = claimCollection[claimType];
else
claims[claimType] = claimCollection[claimType];
}
return claims;
}
/// <summary>
/// Converts a string into an instance of <see cref="JwtSecurityToken"/>.
/// </summary>
/// <param name="token">A 'JSON Web Token' (JWT) in JWS or JWE Compact Serialization Format.</param>
/// <returns>A <see cref="JwtSecurityToken"/></returns>
/// <exception cref="ArgumentNullException"><paramref name="token"/> is null or empty.</exception>
/// <exception cref="ArgumentException">'token.Length' is greater than <see cref="TokenHandler.MaximumTokenSizeInBytes"/>.</exception>
/// <exception cref="SecurityTokenMalformedException"><see cref="CanReadToken(string)"/></exception>
/// <remarks><para>If the <paramref name="token"/> is in JWE Compact Serialization format, only the protected header will be deserialized.
/// This method is unable to decrypt the payload. Use <see cref="ValidateToken(string, TokenValidationParameters, out SecurityToken)"/>to obtain the payload.</para>
/// <para>The token is NOT validated and no security decisions should be made about the contents.
/// Use <see cref="ValidateTokenAsync(string, TokenValidationParameters)"/> to ensure the token is acceptable.</para></remarks>
public JwtSecurityToken ReadJwtToken(string token)
{
if (string.IsNullOrEmpty(token))
throw LogHelper.LogArgumentNullException(nameof(token));
if (token.Length > MaximumTokenSizeInBytes)
throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes))));
if (!CanReadToken(token))
throw LogHelper.LogExceptionMessage(new SecurityTokenMalformedException(LogMessages.IDX12709));
var jwtToken = new JwtSecurityToken();
jwtToken.Decode(token.Split('.'), token);
return jwtToken;
}
/// <summary>
/// Converts a string into an instance of <see cref="JwtSecurityToken"/>.
/// </summary>
/// <param name="token">A 'JSON Web Token' (JWT) in JWS or JWE Compact Serialization Format.</param>
/// <returns>A <see cref="JwtSecurityToken"/></returns>
/// <exception cref="ArgumentNullException"><paramref name="token"/> is null or empty.</exception>
/// <exception cref="ArgumentException">'token.Length' is greater than <see cref="TokenHandler.MaximumTokenSizeInBytes"/>.</exception>
/// <exception cref="ArgumentException"><see cref="CanReadToken(string)"/></exception>
/// <remarks><para>If the <paramref name="token"/> is in JWE Compact Serialization format, only the protected header will be deserialized.</para>
/// This method is unable to decrypt the payload. Use <see cref="ValidateToken(string, TokenValidationParameters, out SecurityToken)"/>to obtain the payload.</remarks>
/// <remarks>The token is NOT validated and no security decisions should be made about the contents.
/// <para>Use <see cref="ValidateTokenAsync(string, TokenValidationParameters)"/> to ensure the token is acceptable.</para></remarks>
public override SecurityToken ReadToken(string token)
{
return ReadJwtToken(token);
}
/// <summary>
/// Deserializes token with the provided <see cref="TokenValidationParameters"/>.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/>.</param>
/// <param name="validationParameters">The <see cref="TokenValidationParameters"/> to be used for validating the token.</param>
/// <returns>The <see cref="SecurityToken"/></returns>
/// <remarks>This method is not current supported.</remarks>
public override SecurityToken ReadToken(XmlReader reader, TokenValidationParameters validationParameters)
{
throw new NotImplementedException();
}
/// <summary>
/// Reads and validates a 'JSON Web Token' (JWT) encoded as a JWS or JWE in Compact Serialized Format.
/// </summary>
/// <param name="token">the JWT encoded as JWE or JWS</param>
/// <param name="validationParameters">The <see cref="TokenValidationParameters"/> to be used for validating the token.</param>
/// <param name="validatedToken">The <see cref="JwtSecurityToken"/> that was validated.</param>
/// <exception cref="ArgumentNullException"><paramref name="token"/> is null or whitespace.</exception>
/// <exception cref="ArgumentNullException"><paramref name="validationParameters"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="token"/>.Length is greater than <see cref="TokenHandler.MaximumTokenSizeInBytes"/>.</exception>
/// <exception cref="SecurityTokenMalformedException"><paramref name="token"/> does not have 3 or 5 parts.</exception>
/// <exception cref="SecurityTokenMalformedException"><see cref="CanReadToken(string)"/> returns false.</exception>
/// <exception cref="SecurityTokenDecryptionFailedException"><paramref name="token"/> was a JWE was not able to be decrypted.</exception>
/// <exception cref="SecurityTokenEncryptionKeyNotFoundException"><paramref name="token"/> 'kid' header claim is not null AND decryption fails.</exception>
/// <exception cref="SecurityTokenException"><paramref name="token"/> 'enc' header claim is null or empty.</exception>
/// <exception cref="SecurityTokenExpiredException"><paramref name="token"/> 'exp' claim is < DateTime.UtcNow.</exception>
/// <exception cref="SecurityTokenInvalidAudienceException"><see cref="TokenValidationParameters.ValidAudience"/> is null or whitespace and <see cref="TokenValidationParameters.ValidAudiences"/> is null. Audience is not validated if <see cref="TokenValidationParameters.ValidateAudience"/> is set to false.</exception>
/// <exception cref="SecurityTokenInvalidAudienceException"><paramref name="token"/> 'aud' claim did not match either <see cref="TokenValidationParameters.ValidAudience"/> or one of <see cref="TokenValidationParameters.ValidAudiences"/>.</exception>
/// <exception cref="SecurityTokenInvalidLifetimeException"><paramref name="token"/> 'nbf' claim is > 'exp' claim.</exception>
/// <exception cref="SecurityTokenInvalidSignatureException"><paramref name="token"/>.signature is not properly formatted.</exception>
/// <exception cref="SecurityTokenNoExpirationException"><paramref name="token"/> 'exp' claim is missing and <see cref="TokenValidationParameters.RequireExpirationTime"/> is true.</exception>
/// <exception cref="SecurityTokenNoExpirationException"><see cref="TokenValidationParameters.TokenReplayCache"/> is not null and expirationTime.HasValue is false. When a TokenReplayCache is set, tokens require an expiration time.</exception>
/// <exception cref="SecurityTokenNotYetValidException"><paramref name="token"/> 'nbf' claim is > DateTime.UtcNow.</exception>
/// <exception cref="SecurityTokenReplayAddFailedException"><paramref name="token"/> could not be added to the <see cref="TokenValidationParameters.TokenReplayCache"/>.</exception>
/// <exception cref="SecurityTokenReplayDetectedException"><paramref name="token"/> is found in the cache.</exception>
/// <returns> A <see cref="ClaimsPrincipal"/> from the JWT. Does not include claims found in the JWT header.</returns>
/// <remarks>
/// Many of the exceptions listed above are not thrown directly from this method. See <see cref="Validators"/> to examine the call graph.
/// </remarks>
public override ClaimsPrincipal ValidateToken(string token, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
if (string.IsNullOrWhiteSpace(token))
throw LogHelper.LogArgumentNullException(nameof(token));
if (validationParameters == null)
throw LogHelper.LogArgumentNullException(nameof(validationParameters));
if (token.Length > MaximumTokenSizeInBytes)
throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(TokenLogMessages.IDX10209, LogHelper.MarkAsNonPII(token.Length), LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes))));
int tokenPartCount = JwtTokenUtilities.CountJwtTokenPart(token, JwtConstants.MaxJwtSegmentCount + 1);
if (tokenPartCount != JwtConstants.JwsSegmentCount && tokenPartCount != JwtConstants.JweSegmentCount)
throw LogHelper.LogExceptionMessage(new SecurityTokenMalformedException(LogMessages.IDX12741));
if (tokenPartCount == JwtConstants.JweSegmentCount)
{
var jwtToken = ReadJwtToken(token);
var decryptedJwt = DecryptToken(jwtToken, validationParameters);
return ValidateToken(decryptedJwt, jwtToken, validationParameters, out validatedToken);
}
else
{
return ValidateToken(token, null, validationParameters, out validatedToken);
}
}
/// <summary>
/// Private method for token validation, responsible for:
/// (1) Obtaining a configuration from the <see cref="TokenValidationParameters.ConfigurationManager"/>.
/// (2) Revalidating using the Last Known Good Configuration (if present), and obtaining a refreshed configuration (if necessary) and revalidating using it.
/// </summary>
/// <param name="token">The JWS string, or the decrypted token if the token is a JWE.</param>
/// <param name="outerToken">If the token being validated is a JWE, this is the <see cref="JwtSecurityToken"/> that represents the outer token.
/// If the token is a JWS, the value of this parameter is <see langword="null" />.
/// </param>
/// <param name="validationParameters">The <see cref="TokenValidationParameters"/> to be used for validation.</param>
/// <param name="signatureValidatedToken">The <see cref="JwtSecurityToken"/> that was validated.</param>
/// <returns> A <see cref="ClaimsPrincipal"/> from the JWT. Does not include claims found in the JWT header.</returns>
private ClaimsPrincipal ValidateToken(string token, JwtSecurityToken outerToken, TokenValidationParameters validationParameters, out SecurityToken signatureValidatedToken)
{
BaseConfiguration currentConfiguration = null;
if (validationParameters.ConfigurationManager != null)
{
try
{
currentConfiguration = validationParameters.ConfigurationManager.GetBaseConfigurationAsync(CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
catch (Exception ex)
{
// The exception is not re-thrown as the TokenValidationParameters may have the issuer and signing key set
// directly on them, allowing the library to continue with token validation.
if (LogHelper.IsEnabled(EventLogLevel.Warning))
LogHelper.LogWarning(LogHelper.FormatInvariant(TokenLogMessages.IDX10261, LogHelper.MarkAsNonPII(validationParameters.ConfigurationManager.MetadataAddress), ex.ToString()));
}
}
ExceptionDispatchInfo exceptionThrown;
ClaimsPrincipal claimsPrincipal = outerToken != null ? ValidateJWE(token, outerToken, validationParameters, currentConfiguration, out signatureValidatedToken, out exceptionThrown) :
ValidateJWS(token, validationParameters, currentConfiguration, out signatureValidatedToken, out exceptionThrown);
if (validationParameters.ConfigurationManager != null)
{
if (claimsPrincipal != null)
{
// Set current configuration as LKG if it exists.
if (currentConfiguration != null)
validationParameters.ConfigurationManager.LastKnownGoodConfiguration = currentConfiguration;
return claimsPrincipal;
}
else if (TokenUtilities.IsRecoverableException(exceptionThrown.SourceException))
{
// If we were still unable to validate, attempt to refresh the configuration and validate using it
// but ONLY if the currentConfiguration is not null. We want to avoid refreshing the configuration on
// retrieval error as this case should have already been hit before. This refresh handles the case
// where a new valid configuration was somehow published during validation time.
if (currentConfiguration != null)
{
validationParameters.ConfigurationManager.RequestRefresh();
validationParameters.RefreshBeforeValidation = true;
var lastConfig = currentConfiguration;
currentConfiguration = validationParameters.ConfigurationManager.GetBaseConfigurationAsync(CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
// Only try to re-validate using the newly obtained config if it doesn't reference equal the previously used configuration.
if (lastConfig != currentConfiguration)
{
claimsPrincipal = outerToken != null ? ValidateJWE(token, outerToken, validationParameters, currentConfiguration, out signatureValidatedToken, out exceptionThrown) :
ValidateJWS(token, validationParameters, currentConfiguration, out signatureValidatedToken, out exceptionThrown);
if (claimsPrincipal != null)
{
validationParameters.ConfigurationManager.LastKnownGoodConfiguration = currentConfiguration;
return claimsPrincipal;
}
}
}
if (validationParameters.ConfigurationManager.UseLastKnownGoodConfiguration)
{
validationParameters.RefreshBeforeValidation = false;
validationParameters.ValidateWithLKG = true;
var recoverableException = exceptionThrown.SourceException;
string kid = outerToken != null ? outerToken.Header.Kid :
(ValidateSignatureUsingDelegates(token, validationParameters, null) ?? GetJwtSecurityTokenFromToken(token, validationParameters)).Header.Kid;
foreach (BaseConfiguration lkgConfiguration in validationParameters.ConfigurationManager.GetValidLkgConfigurations())
{
if (!lkgConfiguration.Equals(currentConfiguration) && TokenUtilities.IsRecoverableConfiguration(kid, currentConfiguration, lkgConfiguration, recoverableException))
{
claimsPrincipal = outerToken != null ? ValidateJWE(token, outerToken, validationParameters, lkgConfiguration, out signatureValidatedToken, out exceptionThrown) :
ValidateJWS(token, validationParameters, lkgConfiguration, out signatureValidatedToken, out exceptionThrown);
if (claimsPrincipal != null)
return claimsPrincipal;
}
}
}
}
}
if (claimsPrincipal != null)
return claimsPrincipal;
exceptionThrown.Throw();
// This should be unreachable code, adding to make the complier happy.
return null;
}
private ClaimsPrincipal ValidateJWE(
string decryptedJwt,
JwtSecurityToken outerToken,
TokenValidationParameters validationParameters,
BaseConfiguration currentConfiguration,
out SecurityToken signatureValidatedToken,
out ExceptionDispatchInfo exceptionThrown)
{
exceptionThrown = null;
try
{
SecurityToken innerToken;
ClaimsPrincipal claimsPrincipal = ValidateJWS(decryptedJwt, validationParameters, currentConfiguration, out innerToken, out exceptionThrown);
outerToken.InnerToken = innerToken as JwtSecurityToken;
signatureValidatedToken = exceptionThrown == null ? outerToken : null;
return claimsPrincipal;
}
catch (Exception ex)
{
exceptionThrown = ExceptionDispatchInfo.Capture(ex);
signatureValidatedToken = null;
return null;
}
}
private ClaimsPrincipal ValidateJWS(
string token,
TokenValidationParameters validationParameters,
BaseConfiguration currentConfiguration,
out SecurityToken signatureValidatedToken,
out ExceptionDispatchInfo exceptionThrown)
{
exceptionThrown = null;
try
{
ClaimsPrincipal claimsPrincipal;
if (validationParameters.SignatureValidator != null || validationParameters.SignatureValidatorUsingConfiguration != null)
{
signatureValidatedToken = ValidateSignatureUsingDelegates(token, validationParameters, currentConfiguration);
claimsPrincipal = ValidateTokenPayload(signatureValidatedToken as JwtSecurityToken, validationParameters, currentConfiguration);
// use protected virtual method that does not take in configuration for back compatibility purposes
if (currentConfiguration == null)
ValidateIssuerSecurityKey(signatureValidatedToken.SigningKey, signatureValidatedToken as JwtSecurityToken, validationParameters);
else
Validators.ValidateIssuerSecurityKey(signatureValidatedToken.SigningKey, signatureValidatedToken, validationParameters, currentConfiguration);
}
else
{
JwtSecurityToken jwtToken = GetJwtSecurityTokenFromToken(token, validationParameters);
if (validationParameters.ValidateSignatureLast)
{
claimsPrincipal = ValidateTokenPayload(jwtToken, validationParameters, currentConfiguration);
jwtToken = ValidateSignatureAndIssuerSecurityKey(token, jwtToken, validationParameters, currentConfiguration);
signatureValidatedToken = jwtToken;
}
else
{
signatureValidatedToken = ValidateSignatureAndIssuerSecurityKey(token, jwtToken, validationParameters, currentConfiguration);