-
Notifications
You must be signed in to change notification settings - Fork 409
/
JsonWebTokenHandler.cs
2069 lines (1781 loc) · 116 KB
/
JsonWebTokenHandler.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;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Abstractions;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using JsonPrimitives = Microsoft.IdentityModel.Tokens.Json.JsonSerializerPrimitives;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
namespace Microsoft.IdentityModel.JsonWebTokens
{
/// <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 JsonWebTokenHandler : TokenHandler
{
private IDictionary<string, string> _inboundClaimTypeMap;
private const string _namespace = "http://schemas.xmlsoap.org/ws/2005/05/identity/claimproperties";
private static string _shortClaimType = _namespace + "/ShortTypeName";
private bool _mapInboundClaims = DefaultMapInboundClaims;
/// <summary>
/// Default claim type mapping for inbound claims.
/// </summary>
public static readonly Dictionary<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 = false;
/// <summary>
/// Gets the Base64Url encoded string representation of the following JWT header:
/// { <see cref="JwtHeaderParameterNames.Alg"/>, <see cref="SecurityAlgorithms.None"/> }.
/// </summary>
/// <return>The Base64Url encoded string representation of the unsigned JWT header.</return>
public const string Base64UrlEncodedUnsignedJWSHeader = "eyJhbGciOiJub25lIn0";
/// <summary>
/// Initializes a new instance of the <see cref="JsonWebTokenHandler"/> class.
/// </summary>
public JsonWebTokenHandler()
{
if (_mapInboundClaims)
_inboundClaimTypeMap = new Dictionary<string, string>(DefaultInboundClaimTypeMap);
else
_inboundClaimTypeMap = new Dictionary<string, string>();
}
/// <summary>
/// Gets the type of the <see cref="JsonWebToken"/>.
/// </summary>
/// <return>The type of <see cref="JsonWebToken"/></return>
public Type TokenType
{
get { return typeof(JsonWebToken); }
}
/// <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.
/// </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 <see cref="MapInboundClaims"/> property which is used when determining whether or not to map claim types that are extracted when validating a <see cref="JsonWebToken"/>.
/// <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 false.</para>
/// </summary>
public bool MapInboundClaims
{
get
{
return _mapInboundClaims;
}
set
{
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="JsonWebToken"/>.
/// <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));
}
}
internal static IDictionary<string, object> AddCtyClaimDefaultValue(IDictionary<string, object> additionalClaims, bool setDefaultCtyClaim)
{
if (!setDefaultCtyClaim)
return additionalClaims;
if (additionalClaims == null)
additionalClaims = new Dictionary<string, object> { { JwtHeaderParameterNames.Cty, JwtConstants.HeaderType } };
else if (!additionalClaims.TryGetValue(JwtHeaderParameterNames.Cty, out _))
additionalClaims.Add(JwtHeaderParameterNames.Cty, JwtConstants.HeaderType);
return additionalClaims;
}
/// <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:
/// <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 virtual 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;
}
// Count the number of segments, which is the number of periods + 1. We can stop when we've encountered
// more segments than the maximum we know how to handle.
int pos = 0;
int segmentCount = 1;
while (segmentCount <= JwtConstants.MaxJwtSegmentCount && ((pos = token.IndexOf('.', pos)) >= 0))
{
pos++;
segmentCount++;
}
switch (segmentCount)
{
case JwtConstants.JwsSegmentCount:
return JwtTokenUtilities.RegexJws.IsMatch(token);
case JwtConstants.JweSegmentCount:
return JwtTokenUtilities.RegexJwe.IsMatch(token);
default:
LogHelper.LogInformation(LogMessages.IDX14107);
return false;
}
}
/// <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="JsonWebToken"/>.</returns>
public virtual bool CanValidateToken
{
get { return true; }
}
/// <summary>
/// Creates an unsigned JWS (Json Web Signature).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <returns>A JWS in Compact Serialization Format.</returns>
public virtual string CreateToken(string payload)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
return CreateToken(Encoding.UTF8.GetBytes(payload), null, null, null, null, null, null);
}
/// <summary>
/// Creates an unsigned JWS (Json Web Signature).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="additionalHeaderClaims">Defines the dictionary containing any custom header claims that need to be added to the JWT token header.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="additionalHeaderClaims"/> is null.</exception>
/// <returns>A JWS in Compact Serialization Format.</returns>
public virtual string CreateToken(string payload, IDictionary<string, object> additionalHeaderClaims)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (additionalHeaderClaims == null)
throw LogHelper.LogArgumentNullException(nameof(additionalHeaderClaims));
return CreateToken(Encoding.UTF8.GetBytes(payload), null, null, null, additionalHeaderClaims, null, null);
}
/// <summary>
/// Creates a JWS (Json Web Signature).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="signingCredentials">Defines the security key and algorithm that will be used to sign the JWS.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="signingCredentials"/> is null.</exception>
/// <returns>A JWS in Compact Serialization Format.</returns>
public virtual string CreateToken(string payload, SigningCredentials signingCredentials)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
return CreateToken(Encoding.UTF8.GetBytes(payload), signingCredentials, null, null, null, null, null);
}
/// <summary>
/// Creates a JWS (Json Web Signature).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="signingCredentials">Defines the security key and algorithm that will be used to sign the JWS.</param>
/// <param name="additionalHeaderClaims">Defines the dictionary containing any custom header claims that need to be added to the JWT token header.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="signingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="additionalHeaderClaims"/> is null.</exception>
/// <exception cref="SecurityTokenException">if <see cref="JwtHeaderParameterNames.Alg"/>, <see cref="JwtHeaderParameterNames.Kid"/>
/// <see cref="JwtHeaderParameterNames.X5t"/>, <see cref="JwtHeaderParameterNames.Enc"/>, and/or <see cref="JwtHeaderParameterNames.Zip"/>
/// are present inside of <paramref name="additionalHeaderClaims"/>.</exception>
/// <returns>A JWS in Compact Serialization Format.</returns>
public virtual string CreateToken(string payload, SigningCredentials signingCredentials, IDictionary<string, object> additionalHeaderClaims)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
if (additionalHeaderClaims == null)
throw LogHelper.LogArgumentNullException(nameof(additionalHeaderClaims));
return CreateToken(Encoding.UTF8.GetBytes(payload), signingCredentials, null, null, additionalHeaderClaims, null, null);
}
/// <summary>
/// Creates a JWS(Json Web Signature).
/// </summary>
/// <param name="tokenDescriptor">A <see cref="SecurityTokenDescriptor"/> that contains details of contents of the token.</param>
/// <returns>A JWS in Compact Serialization Format.</returns>
public virtual string CreateToken(SecurityTokenDescriptor tokenDescriptor)
{
_ = tokenDescriptor ?? throw LogHelper.LogArgumentNullException(nameof(tokenDescriptor));
if (LogHelper.IsEnabled(EventLogLevel.Warning))
{
if ((tokenDescriptor.Subject == null || !tokenDescriptor.Subject.Claims.Any())
&& (tokenDescriptor.Claims == null || !tokenDescriptor.Claims.Any()))
LogHelper.LogWarning(
LogMessages.IDX14114, LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor)), LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor.Subject)), LogHelper.MarkAsNonPII(nameof(SecurityTokenDescriptor.Claims)));
}
return CreateToken(
WritePayload(tokenDescriptor),
tokenDescriptor.SigningCredentials,
tokenDescriptor.EncryptingCredentials,
tokenDescriptor.CompressionAlgorithm,
tokenDescriptor.AdditionalHeaderClaims,
tokenDescriptor.AdditionalInnerHeaderClaims,
tokenDescriptor.TokenType);
}
internal static byte[] WriteJwsHeader(
SigningCredentials signingCredentials,
string tokenType,
IDictionary<string, object> jwsHeaderClaims,
IDictionary<string, object> jweHeaderClaims)
{
using (MemoryStream memoryStream = new MemoryStream())
{
Utf8JsonWriter writer = null;
try
{
writer = new Utf8JsonWriter(memoryStream, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
writer.WriteStartObject();
if (signingCredentials == null)
{
writer.WriteString(JwtHeaderUtf8Bytes.Alg, SecurityAlgorithms.None);
}
else
{
writer.WriteString(JwtHeaderUtf8Bytes.Alg, signingCredentials.Algorithm);
if (signingCredentials.Key.KeyId != null)
writer.WriteString(JwtHeaderUtf8Bytes.Kid, signingCredentials.Key.KeyId);
if (signingCredentials.Key is X509SecurityKey x509SecurityKey)
writer.WriteString(JwtHeaderUtf8Bytes.X5t, x509SecurityKey.X5t);
}
bool useJwsHeaderClaims = jwsHeaderClaims != null && jwsHeaderClaims.Count > 0;
bool typeWritten = false;
// Priority is jwsHeaderClaims, jweHeaderClaims, default
if (jweHeaderClaims != null && jweHeaderClaims.Count > 0)
{
foreach (KeyValuePair<string, object> kvp in jweHeaderClaims)
{
if (useJwsHeaderClaims && jwsHeaderClaims.ContainsKey(kvp.Key))
continue;
JsonPrimitives.WriteObject(ref writer, kvp.Key, kvp.Value);
if (!typeWritten && kvp.Key.Equals(JwtHeaderParameterNames.Typ, StringComparison.Ordinal))
typeWritten = true;
}
}
if (useJwsHeaderClaims)
{
foreach (KeyValuePair<string, object> kvp in jwsHeaderClaims)
{
JsonPrimitives.WriteObject(ref writer, kvp.Key, kvp.Value);
if (!typeWritten && kvp.Key.Equals(JwtHeaderParameterNames.Typ, StringComparison.Ordinal))
typeWritten = true;
}
}
if (!typeWritten)
writer.WriteString(JwtHeaderUtf8Bytes.Typ, string.IsNullOrEmpty(tokenType) ? JwtConstants.HeaderType : tokenType);
writer.WriteEndObject();
writer.Flush();
return memoryStream.ToArray();
}
finally
{
writer?.Dispose();
}
}
}
internal static byte[] WriteJweHeader(
EncryptingCredentials encryptingCredentials,
string compressionAlgorithm,
string tokenType,
IDictionary<string, object> jweHeaderClaims)
{
using (MemoryStream memoryStream = new MemoryStream())
{
Utf8JsonWriter writer = null;
try
{
writer = new Utf8JsonWriter(memoryStream, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
writer.WriteStartObject();
writer.WriteString(JwtHeaderUtf8Bytes.Alg, encryptingCredentials.Alg);
writer.WriteString(JwtHeaderUtf8Bytes.Enc, encryptingCredentials.Enc);
if (encryptingCredentials.Key.KeyId != null)
writer.WriteString(JwtHeaderUtf8Bytes.Kid, encryptingCredentials.Key.KeyId);
if (!string.IsNullOrEmpty(compressionAlgorithm))
writer.WriteString(JwtHeaderUtf8Bytes.Zip, compressionAlgorithm);
bool typeWritten = false;
bool ctyWritten = !encryptingCredentials.SetDefaultCtyClaim;
// Current 6x Priority is jweHeaderClaims, type, cty
if (jweHeaderClaims != null && jweHeaderClaims.Count > 0)
{
foreach (KeyValuePair<string, object> kvp in jweHeaderClaims)
{
JsonPrimitives.WriteObject(ref writer, kvp.Key, kvp.Value);
if (!typeWritten && kvp.Key.Equals(JwtHeaderParameterNames.Typ, StringComparison.Ordinal))
typeWritten = true;
else if (!ctyWritten && kvp.Key.Equals(JwtHeaderParameterNames.Cty, StringComparison.Ordinal))
ctyWritten = true;
}
}
if (!typeWritten)
writer.WriteString(JwtHeaderUtf8Bytes.Typ, string.IsNullOrEmpty(tokenType) ? JwtConstants.HeaderType : tokenType);
if (!ctyWritten)
writer.WriteString(JwtHeaderUtf8Bytes.Cty, JwtConstants.HeaderType);
writer.WriteEndObject();
writer.Flush();
return memoryStream.ToArray();
}
finally
{
writer?.Dispose();
}
}
}
internal byte[] WritePayload(SecurityTokenDescriptor tokenDescriptor)
{
bool audienceSet = !string.IsNullOrEmpty(tokenDescriptor.Audience);
bool issuerSet = !string.IsNullOrEmpty(tokenDescriptor.Issuer);
IDictionary<string, object> payload = TokenUtilities.CreateDictionaryFromClaims(tokenDescriptor.Subject?.Claims, tokenDescriptor, audienceSet, issuerSet);
// Duplicates are resolved according to the following priority:
// SecurityTokenDescriptor.{Audience, Issuer, Expires, IssuedAt, NotBefore}, SecurityTokenDescriptor.Claims, SecurityTokenDescriptor.Subject.Claims
if (tokenDescriptor.Claims != null && tokenDescriptor.Claims.Count > 0)
{
foreach (var kvp in tokenDescriptor.Claims)
{
if (audienceSet && kvp.Key.Equals("aud", StringComparison.Ordinal))
continue;
if (issuerSet && kvp.Key.Equals("iss", StringComparison.Ordinal))
continue;
if (tokenDescriptor.Expires.HasValue && kvp.Key.Equals("exp", StringComparison.Ordinal))
continue;
if (tokenDescriptor.IssuedAt.HasValue && kvp.Key.Equals("iat", StringComparison.Ordinal))
continue;
if (tokenDescriptor.NotBefore.HasValue && kvp.Key.Equals("nbf", StringComparison.Ordinal))
continue;
payload[kvp.Key] = kvp.Value;
}
}
bool expiresSet = false;
bool nbfSet = false;
bool iatSet = false;
if (audienceSet)
{
if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Aud))
LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.Audience))));
payload[JwtRegisteredClaimNames.Aud] = tokenDescriptor.Audience;
}
if (issuerSet)
{
if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Iss))
LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.Issuer))));
payload[JwtRegisteredClaimNames.Iss] = tokenDescriptor.Issuer;
}
if (tokenDescriptor.Expires.HasValue)
{
if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Exp))
LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.Expires))));
payload[JwtRegisteredClaimNames.Exp] = EpochTime.GetIntDate(tokenDescriptor.Expires.Value);
expiresSet = true;
}
if (tokenDescriptor.IssuedAt.HasValue)
{
if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Iat))
LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.IssuedAt))));
payload[JwtRegisteredClaimNames.Iat] = EpochTime.GetIntDate(tokenDescriptor.IssuedAt.Value);
iatSet = true;
}
if (tokenDescriptor.NotBefore.HasValue)
{
if (LogHelper.IsEnabled(EventLogLevel.Informational) && payload.ContainsKey(JwtRegisteredClaimNames.Nbf))
LogHelper.LogInformation(LogHelper.FormatInvariant(LogMessages.IDX14113, LogHelper.MarkAsNonPII(nameof(tokenDescriptor.NotBefore))));
payload[JwtRegisteredClaimNames.Nbf] = EpochTime.GetIntDate(tokenDescriptor.NotBefore.Value);
nbfSet = true;
}
// by default we set these three properties only if they haven't been set.
if (SetDefaultTimesOnTokenCreation)
{
long now = EpochTime.GetIntDate(DateTime.UtcNow);
if (!expiresSet && !payload.ContainsKey(JwtRegisteredClaimNames.Exp))
payload.Add(JwtRegisteredClaimNames.Exp, now + TokenLifetimeInMinutes * 60);
if (!iatSet && !payload.ContainsKey(JwtRegisteredClaimNames.Iat))
payload.Add(JwtRegisteredClaimNames.Iat, now);
if (!nbfSet && !payload.ContainsKey(JwtRegisteredClaimNames.Nbf))
payload.Add(JwtRegisteredClaimNames.Nbf, now);
}
using (MemoryStream memoryStream = new())
{
Utf8JsonWriter writer = null;
try
{
writer = new Utf8JsonWriter(memoryStream, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
writer.WriteStartObject();
foreach (KeyValuePair<string, object> kvp in payload)
{
if (kvp.Value is IList<object> l)
{
writer.WriteStartArray(kvp.Key);
foreach (object obj in l)
JsonPrimitives.WriteObjectValue(ref writer, obj);
writer.WriteEndArray();
}
else
{
JsonPrimitives.WriteObject(ref writer, kvp.Key, kvp.Value);
}
}
writer.WriteEndObject();
writer.Flush();
return memoryStream.ToArray();
}
finally
{
writer?.Dispose();
}
}
}
/// <summary>
/// Creates a JWE (Json Web Encryption).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="encryptingCredentials">Defines the security key and algorithm that will be used to encrypt the JWT.</param>
/// <returns>A JWE in compact serialization format.</returns>
public virtual string CreateToken(string payload, EncryptingCredentials encryptingCredentials)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
return CreateToken(Encoding.UTF8.GetBytes(payload), null, encryptingCredentials, null, null, null, null);
}
/// <summary>
/// Creates a JWE (Json Web Encryption).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="encryptingCredentials">Defines the security key and algorithm that will be used to encrypt the JWT.</param>
/// <param name="additionalHeaderClaims">Defines the dictionary containing any custom header claims that need to be added to the outer JWT token header.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="encryptingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="additionalHeaderClaims"/> is null.</exception>
/// <exception cref="SecurityTokenException">if <see cref="JwtHeaderParameterNames.Alg"/>, <see cref="JwtHeaderParameterNames.Kid"/>
/// <see cref="JwtHeaderParameterNames.X5t"/>, <see cref="JwtHeaderParameterNames.Enc"/>, and/or <see cref="JwtHeaderParameterNames.Zip"/>
/// are present inside of <paramref name="additionalHeaderClaims"/>.</exception>
/// <returns>A JWS in Compact Serialization Format.</returns>
public virtual string CreateToken(string payload, EncryptingCredentials encryptingCredentials, IDictionary<string, object> additionalHeaderClaims)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
if (additionalHeaderClaims == null)
throw LogHelper.LogArgumentNullException(nameof(additionalHeaderClaims));
return CreateToken(Encoding.UTF8.GetBytes(payload), null, encryptingCredentials, null, additionalHeaderClaims, null, null);
}
/// <summary>
/// Creates a JWE (Json Web Encryption).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="signingCredentials">Defines the security key and algorithm that will be used to sign the JWT.</param>
/// <param name="encryptingCredentials">Defines the security key and algorithm that will be used to encrypt the JWT.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="signingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="encryptingCredentials"/> is null.</exception>
/// <returns>A JWE in compact serialization format.</returns>
public virtual string CreateToken(string payload, SigningCredentials signingCredentials, EncryptingCredentials encryptingCredentials)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
return CreateToken(Encoding.UTF8.GetBytes(payload), signingCredentials, encryptingCredentials, null, null, null, null);
}
/// <summary>
/// Creates a JWE (Json Web Encryption).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="signingCredentials">Defines the security key and algorithm that will be used to sign the JWT.</param>
/// <param name="encryptingCredentials">Defines the security key and algorithm that will be used to encrypt the JWT.</param>
/// <param name="additionalHeaderClaims">Defines the dictionary containing any custom header claims that need to be added to the outer JWT token header.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="signingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="encryptingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="additionalHeaderClaims"/> is null.</exception>
/// <exception cref="SecurityTokenException">if <see cref="JwtHeaderParameterNames.Alg"/>, <see cref="JwtHeaderParameterNames.Kid"/>
/// <see cref="JwtHeaderParameterNames.X5t"/>, <see cref="JwtHeaderParameterNames.Enc"/>, and/or <see cref="JwtHeaderParameterNames.Zip"/>
/// are present inside of <paramref name="additionalHeaderClaims"/>.</exception>
/// <returns>A JWE in compact serialization format.</returns>
public virtual string CreateToken(
string payload,
SigningCredentials signingCredentials,
EncryptingCredentials encryptingCredentials,
IDictionary<string, object> additionalHeaderClaims)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
if (additionalHeaderClaims == null)
throw LogHelper.LogArgumentNullException(nameof(additionalHeaderClaims));
return CreateToken(Encoding.UTF8.GetBytes(payload), signingCredentials, encryptingCredentials, null, additionalHeaderClaims, null, null);
}
/// <summary>
/// Creates a JWE (Json Web Encryption).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="encryptingCredentials">Defines the security key and algorithm that will be used to encrypt the JWT.</param>
/// <param name="compressionAlgorithm">Defines the compression algorithm that will be used to compress the JWT token payload.</param>
/// <returns>A JWE in compact serialization format.</returns>
public virtual string CreateToken(string payload, EncryptingCredentials encryptingCredentials, string compressionAlgorithm)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
if (string.IsNullOrEmpty(compressionAlgorithm))
throw LogHelper.LogArgumentNullException(nameof(compressionAlgorithm));
return CreateToken(Encoding.UTF8.GetBytes(payload), null, encryptingCredentials, compressionAlgorithm, null, null, null);
}
/// <summary>
/// Creates a JWE (Json Web Encryption).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="signingCredentials">Defines the security key and algorithm that will be used to sign the JWT.</param>
/// <param name="encryptingCredentials">Defines the security key and algorithm that will be used to encrypt the JWT.</param>
/// <param name="compressionAlgorithm">Defines the compression algorithm that will be used to compress the JWT token payload.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="signingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="encryptingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="compressionAlgorithm"/> is null.</exception>
/// <returns>A JWE in compact serialization format.</returns>
public virtual string CreateToken(string payload, SigningCredentials signingCredentials, EncryptingCredentials encryptingCredentials, string compressionAlgorithm)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
if (string.IsNullOrEmpty(compressionAlgorithm))
throw LogHelper.LogArgumentNullException(nameof(compressionAlgorithm));
return CreateToken(Encoding.UTF8.GetBytes(payload), signingCredentials, encryptingCredentials, compressionAlgorithm, null, null, null);
}
/// <summary>
/// Creates a JWE (Json Web Encryption).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="signingCredentials">Defines the security key and algorithm that will be used to sign the JWT.</param>
/// <param name="encryptingCredentials">Defines the security key and algorithm that will be used to encrypt the JWT.</param>
/// <param name="compressionAlgorithm">Defines the compression algorithm that will be used to compress the JWT token payload.</param>
/// <param name="additionalHeaderClaims">Defines the dictionary containing any custom header claims that need to be added to the outer JWT token header.</param>
/// <param name="additionalInnerHeaderClaims">Defines the dictionary containing any custom header claims that need to be added to the inner JWT token header.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="signingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="encryptingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="compressionAlgorithm"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="additionalHeaderClaims"/> is null.</exception>
/// <exception cref="SecurityTokenException">if <see cref="JwtHeaderParameterNames.Alg"/>, <see cref="JwtHeaderParameterNames.Kid"/>
/// <see cref="JwtHeaderParameterNames.X5t"/>, <see cref="JwtHeaderParameterNames.Enc"/>, and/or <see cref="JwtHeaderParameterNames.Zip"/>
/// are present inside of <paramref name="additionalHeaderClaims"/>.</exception>
/// <returns>A JWE in compact serialization format.</returns>
public virtual string CreateToken(
string payload,
SigningCredentials signingCredentials,
EncryptingCredentials encryptingCredentials,
string compressionAlgorithm,
IDictionary<string, object> additionalHeaderClaims,
IDictionary<string, object> additionalInnerHeaderClaims)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
if (string.IsNullOrEmpty(compressionAlgorithm))
throw LogHelper.LogArgumentNullException(nameof(compressionAlgorithm));
if (additionalHeaderClaims == null)
throw LogHelper.LogArgumentNullException(nameof(additionalHeaderClaims));
if (additionalInnerHeaderClaims == null)
throw LogHelper.LogArgumentNullException(nameof(additionalInnerHeaderClaims));
return CreateToken(
Encoding.UTF8.GetBytes(payload),
signingCredentials,
encryptingCredentials,
compressionAlgorithm,
additionalHeaderClaims,
additionalInnerHeaderClaims,
null);
}
/// <summary>
/// Creates a JWE (Json Web Encryption).
/// </summary>
/// <param name="payload">A string containing JSON which represents the JWT token payload.</param>
/// <param name="signingCredentials">Defines the security key and algorithm that will be used to sign the JWT.</param>
/// <param name="encryptingCredentials">Defines the security key and algorithm that will be used to encrypt the JWT.</param>
/// <param name="compressionAlgorithm">Defines the compression algorithm that will be used to compress the JWT token payload.</param>
/// <param name="additionalHeaderClaims">Defines the dictionary containing any custom header claims that need to be added to the outer JWT token header.</param>
/// <exception cref="ArgumentNullException">if <paramref name="payload"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="signingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="encryptingCredentials"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="compressionAlgorithm"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="additionalHeaderClaims"/> is null.</exception>
/// <exception cref="SecurityTokenException">if <see cref="JwtHeaderParameterNames.Alg"/>, <see cref="JwtHeaderParameterNames.Kid"/>
/// <see cref="JwtHeaderParameterNames.X5t"/>, <see cref="JwtHeaderParameterNames.Enc"/>, and/or <see cref="JwtHeaderParameterNames.Zip"/>
/// are present inside of <paramref name="additionalHeaderClaims"/>.</exception>
/// <returns>A JWE in compact serialization format.</returns>
public virtual string CreateToken(
string payload,
SigningCredentials signingCredentials,
EncryptingCredentials encryptingCredentials,
string compressionAlgorithm,
IDictionary<string, object> additionalHeaderClaims)
{
if (string.IsNullOrEmpty(payload))
throw LogHelper.LogArgumentNullException(nameof(payload));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
if (encryptingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(encryptingCredentials));
if (string.IsNullOrEmpty(compressionAlgorithm))
throw LogHelper.LogArgumentNullException(nameof(compressionAlgorithm));
if (additionalHeaderClaims == null)
throw LogHelper.LogArgumentNullException(nameof(additionalHeaderClaims));
return CreateToken(Encoding.UTF8.GetBytes(payload), signingCredentials, encryptingCredentials, compressionAlgorithm, additionalHeaderClaims, null, null);
}
internal static string CreateToken
(
byte[] payloadBytes,
SigningCredentials signingCredentials,
EncryptingCredentials encryptingCredentials,
string compressionAlgorithm,
IDictionary<string, object> additionalHeaderClaims,
IDictionary<string, object> additionalInnerHeaderClaims,
string tokenType)
{
// TODO - Create one Span<byte> to write everything into and avoid moving between string -> Utf8Bytes -> string + string -> Utf8bytes.
// The Header, Payload, Message, etc.
// Avoid creating and writing to MemoryStreams and then calling ToArray();
// Rent ArrayPools
// Would like to use, but the following is internal.
// Will see how hard it is to use the code.
// ArrayBufferWriter<byte> buffer = new System.Buffers.ArrayBufferWriter<byte>();
// C:\github\dotnet\runtime\src\libraries\Common\src\System\Buffers\ArrayBufferWriter.cs
// If we can't use ArrayBufferWriter, we can make use our own pool in tokens.
// A possibility is to use our internal pool: sealed class DisposableObjectPool<T> where T : class, IDisposable
// When creating an Encrypted Token, pass in a Span<byte>, representing the inner token.
if (additionalHeaderClaims?.Count > 0 && additionalHeaderClaims.Keys.Intersect(JwtTokenUtilities.DefaultHeaderParameters, StringComparer.OrdinalIgnoreCase).Any())
throw LogHelper.LogExceptionMessage(new SecurityTokenException(LogHelper.FormatInvariant(LogMessages.IDX14116, LogHelper.MarkAsNonPII(nameof(additionalHeaderClaims)), LogHelper.MarkAsNonPII(string.Join(", ", JwtTokenUtilities.DefaultHeaderParameters)))));
if (additionalInnerHeaderClaims?.Count > 0 && additionalInnerHeaderClaims.Keys.Intersect(JwtTokenUtilities.DefaultHeaderParameters, StringComparer.OrdinalIgnoreCase).Any())
throw LogHelper.LogExceptionMessage(new SecurityTokenException(LogHelper.FormatInvariant(LogMessages.IDX14116, nameof(additionalInnerHeaderClaims), string.Join(", ", JwtTokenUtilities.DefaultHeaderParameters))));
byte[] headerBytes = WriteJwsHeader(signingCredentials, tokenType, additionalInnerHeaderClaims, encryptingCredentials == null ? additionalHeaderClaims : null);
string header = Base64UrlEncoder.Encode(headerBytes);
string message = header + "." + Base64UrlEncoder.Encode(payloadBytes);
var rawSignature = signingCredentials == null ? string.Empty : JwtTokenUtilities.CreateEncodedSignature(message, signingCredentials);
if (encryptingCredentials != null)
return EncryptToken(Encoding.UTF8.GetBytes(message + "." + rawSignature), encryptingCredentials, compressionAlgorithm, additionalHeaderClaims, tokenType);
return message + "." + rawSignature;
}
internal static byte[] CompressToken(byte[] utf8Bytes, string compressionAlgorithm)
{
if (string.IsNullOrEmpty(compressionAlgorithm))
throw LogHelper.LogArgumentNullException(nameof(compressionAlgorithm));
if (!CompressionProviderFactory.Default.IsSupportedAlgorithm(compressionAlgorithm))
throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10682, LogHelper.MarkAsNonPII(compressionAlgorithm))));
var compressionProvider = CompressionProviderFactory.Default.CreateCompressionProvider(compressionAlgorithm);
return compressionProvider.Compress(utf8Bytes) ?? throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(TokenLogMessages.IDX10680, LogHelper.MarkAsNonPII(compressionAlgorithm))));
}
private static StringComparison GetStringComparisonRuleIf509(SecurityKey securityKey) => (securityKey is X509SecurityKey)
? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
private static StringComparison GetStringComparisonRuleIf509OrECDsa(SecurityKey securityKey) => (securityKey is X509SecurityKey
|| securityKey is ECDsaSecurityKey)
? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
/// <summary>
/// Creates a <see cref="ClaimsIdentity"/> from a <see cref="JsonWebToken"/>.
/// </summary>
/// <param name="jwtToken">The <see cref="JsonWebToken"/> to use as a <see cref="Claim"/> source.</param>
/// <param name="validationParameters"> Contains parameters for validating the token.</param>
/// <returns>A <see cref="ClaimsIdentity"/> containing the <see cref="JsonWebToken.Claims"/>.</returns>
protected virtual ClaimsIdentity CreateClaimsIdentity(JsonWebToken jwtToken, TokenValidationParameters validationParameters)
{
_ = jwtToken ?? throw LogHelper.LogArgumentNullException(nameof(jwtToken));
return CreateClaimsIdentityPrivate(jwtToken, validationParameters, GetActualIssuer(jwtToken));
}
/// <summary>
/// Creates a <see cref="ClaimsIdentity"/> from a <see cref="JsonWebToken"/> with the specified issuer.
/// </summary>
/// <param name="jwtToken">The <see cref="JsonWebToken"/> to use as a <see cref="Claim"/> source.</param>
/// <param name="validationParameters">Contains parameters for validating the token.</param>
/// <param name="issuer">Specifies the issuer for the <see cref="ClaimsIdentity"/>.</param>
/// <returns>A <see cref="ClaimsIdentity"/> containing the <see cref="JsonWebToken.Claims"/>.</returns>
protected virtual ClaimsIdentity CreateClaimsIdentity(JsonWebToken jwtToken, TokenValidationParameters validationParameters, string issuer)
{
_ = jwtToken ?? throw LogHelper.LogArgumentNullException(nameof(jwtToken));
if (string.IsNullOrWhiteSpace(issuer))
issuer = GetActualIssuer(jwtToken);
if (MapInboundClaims)
return CreateClaimsIdentityWithMapping(jwtToken, validationParameters, issuer);
return CreateClaimsIdentityPrivate(jwtToken, validationParameters, issuer);
}
private ClaimsIdentity CreateClaimsIdentityWithMapping(JsonWebToken jwtToken, TokenValidationParameters validationParameters, string issuer)
{
_ = validationParameters ?? throw LogHelper.LogArgumentNullException(nameof(validationParameters));
ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(jwtToken, issuer);
foreach (Claim jwtClaim in jwtToken.Claims)
{
bool wasMapped = _inboundClaimTypeMap.TryGetValue(jwtClaim.Type, out string claimType);
if (!wasMapped)
claimType = jwtClaim.Type;
if (claimType == ClaimTypes.Actor)
{
if (identity.Actor != null)
throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(
LogMessages.IDX14112,
LogHelper.MarkAsNonPII(JwtRegisteredClaimNames.Actort),
jwtClaim.Value)));
if (CanReadToken(jwtClaim.Value))
{
JsonWebToken actor = ReadToken(jwtClaim.Value) as JsonWebToken;
identity.Actor = CreateClaimsIdentity(actor, validationParameters);
}
}
if (wasMapped)
{
Claim claim = new Claim(claimType, jwtClaim.Value, jwtClaim.ValueType, issuer, issuer, identity);
if (jwtClaim.Properties.Count > 0)
{
foreach (var kv in jwtClaim.Properties)
{
claim.Properties[kv.Key] = kv.Value;
}
}
claim.Properties[ShortClaimTypeProperty] = jwtClaim.Type;
identity.AddClaim(claim);
}
else
{
identity.AddClaim(jwtClaim);
}
}
return identity;
}
internal override ClaimsIdentity CreateClaimsIdentityInternal(SecurityToken securityToken, TokenValidationParameters tokenValidationParameters, string issuer)
{
return CreateClaimsIdentity(securityToken as JsonWebToken, tokenValidationParameters, issuer);
}
private static string GetActualIssuer(JsonWebToken jwtToken)
{
string actualIssuer = jwtToken.Issuer;
if (string.IsNullOrWhiteSpace(actualIssuer))
{
if (LogHelper.IsEnabled(EventLogLevel.Verbose))
LogHelper.LogVerbose(TokenLogMessages.IDX10244, ClaimsIdentity.DefaultIssuer);
actualIssuer = ClaimsIdentity.DefaultIssuer;
}
return actualIssuer;
}
private ClaimsIdentity CreateClaimsIdentityPrivate(JsonWebToken jwtToken, TokenValidationParameters validationParameters, string issuer)
{
_ = validationParameters ?? throw LogHelper.LogArgumentNullException(nameof(validationParameters));
ClaimsIdentity identity = validationParameters.CreateClaimsIdentity(jwtToken, issuer);
foreach (Claim jwtClaim in jwtToken.Claims)
{
string claimType = jwtClaim.Type;
if (claimType == ClaimTypes.Actor)
{
if (identity.Actor != null)
throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX14112, LogHelper.MarkAsNonPII(JwtRegisteredClaimNames.Actort), jwtClaim.Value)));
if (CanReadToken(jwtClaim.Value))
{
JsonWebToken actor = ReadToken(jwtClaim.Value) as JsonWebToken;
identity.Actor = CreateClaimsIdentity(actor, validationParameters, issuer);
}
}
if (jwtClaim.Properties.Count == 0)