-
Notifications
You must be signed in to change notification settings - Fork 462
Expand file tree
/
Copy pathJwtTokenUtilities.cs
More file actions
625 lines (538 loc) · 31.8 KB
/
JwtTokenUtilities.cs
File metadata and controls
625 lines (538 loc) · 31.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.IdentityModel.Abstractions;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens.Json;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
namespace Microsoft.IdentityModel.JsonWebTokens
{
/// <summary>
/// A class which contains useful methods for processing JWT tokens.
/// </summary>
public partial class JwtTokenUtilities
{
private const int _regexMatchTimeoutMilliseconds = 100;
private const string _unrecognizedEncodedToken = "UnrecognizedEncodedToken";
/// <summary>
/// Regex that is used to figure out if a token is in JWS format.
/// </summary>
public static Regex RegexJws = CreateJwsRegex();
/// <summary>
/// Regex that is used to figure out if a token is in JWE format.
/// </summary>
public static Regex RegexJwe = CreateJweRegex();
#if NET7_0_OR_GREATER
[GeneratedRegex(JwtConstants.JsonCompactSerializationRegex, RegexOptions.CultureInvariant, _regexMatchTimeoutMilliseconds)]
private static partial Regex CreateJwsRegex();
[GeneratedRegex(JwtConstants.JweCompactSerializationRegex, RegexOptions.CultureInvariant, _regexMatchTimeoutMilliseconds)]
private static partial Regex CreateJweRegex();
#else
private static Regex CreateJwsRegex() => new Regex(JwtConstants.JsonCompactSerializationRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(_regexMatchTimeoutMilliseconds));
private static Regex CreateJweRegex() => new Regex(JwtConstants.JweCompactSerializationRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(_regexMatchTimeoutMilliseconds));
#endif
internal static List<string> DefaultHeaderParameters = new List<string>()
{
JwtHeaderParameterNames.Alg,
JwtHeaderParameterNames.Kid,
JwtHeaderParameterNames.X5t,
JwtHeaderParameterNames.Enc,
JwtHeaderParameterNames.Zip
};
/// <summary>
/// Produces a signature over the <paramref name="input"/>.
/// </summary>
/// <param name="input">String to be signed</param>
/// <param name="signingCredentials">The <see cref="SigningCredentials"/> that contain crypto specs used to sign the token.</param>
/// <returns>The base 64 url encoded signature over the bytes obtained from UTF8Encoding.GetBytes( 'input' ).</returns>
/// <exception cref="ArgumentNullException">'input' or 'signingCredentials' is null.</exception>
public static string CreateEncodedSignature(string input, SigningCredentials signingCredentials)
{
if (input == null)
throw LogHelper.LogArgumentNullException(nameof(input));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
var cryptoProviderFactory = signingCredentials.CryptoProviderFactory ?? signingCredentials.Key.CryptoProviderFactory;
var signatureProvider = cryptoProviderFactory.CreateForSigning(signingCredentials.Key, signingCredentials.Algorithm);
if (signatureProvider == null)
throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(TokenLogMessages.IDX10637, signingCredentials.Key == null ? "Null" : signingCredentials.Key.ToString(), LogHelper.MarkAsNonPII(signingCredentials.Algorithm))));
try
{
LogHelper.LogVerbose(LogMessages.IDX14200);
return Base64UrlEncoder.Encode(signatureProvider.Sign(Encoding.UTF8.GetBytes(input)));
}
finally
{
cryptoProviderFactory.ReleaseSignatureProvider(signatureProvider);
}
}
/// <summary>
/// Produces a signature over the <paramref name="input"/>.
/// </summary>
/// <param name="input">String to be signed</param>
/// <param name="signingCredentials">The <see cref="SigningCredentials"/> that contain crypto specs used to sign the token.</param>
/// <param name="cacheProvider">should the <see cref="SignatureProvider"/> be cached.</param>
/// <returns>The base 64 url encoded signature over the bytes obtained from UTF8Encoding.GetBytes( 'input' ).</returns>
/// <exception cref="ArgumentNullException"><paramref name="input"/> or <paramref name="signingCredentials"/> is null.</exception>
public static string CreateEncodedSignature(string input, SigningCredentials signingCredentials, bool cacheProvider)
{
if (input == null)
throw LogHelper.LogArgumentNullException(nameof(input));
if (signingCredentials == null)
throw LogHelper.LogArgumentNullException(nameof(signingCredentials));
var cryptoProviderFactory = signingCredentials.CryptoProviderFactory ?? signingCredentials.Key.CryptoProviderFactory;
var signatureProvider = cryptoProviderFactory.CreateForSigning(signingCredentials.Key, signingCredentials.Algorithm, cacheProvider);
if (signatureProvider == null)
throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(TokenLogMessages.IDX10637, signingCredentials.Key == null ? "Null" : signingCredentials.Key.ToString(), LogHelper.MarkAsNonPII(signingCredentials.Algorithm))));
try
{
if (LogHelper.IsEnabled(EventLogLevel.Verbose))
LogHelper.LogVerbose(LogHelper.FormatInvariant(LogMessages.IDX14201, LogHelper.MarkAsNonPII(cacheProvider)));
return Base64UrlEncoder.Encode(signatureProvider.Sign(Encoding.UTF8.GetBytes(input)));
}
finally
{
cryptoProviderFactory.ReleaseSignatureProvider(signatureProvider);
}
}
internal static byte[] CreateEncodedSignature(
byte[] input,
int offset,
int count,
SigningCredentials signingCredentials)
{
if (input == null)
throw LogHelper.LogArgumentNullException(nameof(input));
if (signingCredentials == null)
return null;
var cryptoProviderFactory = signingCredentials.CryptoProviderFactory ?? signingCredentials.Key.CryptoProviderFactory;
var signatureProvider = cryptoProviderFactory.CreateForSigning(signingCredentials.Key, signingCredentials.Algorithm) ??
throw LogHelper.LogExceptionMessage(
new InvalidOperationException(
LogHelper.FormatInvariant(
TokenLogMessages.IDX10637,
signingCredentials.Key == null ? "Null" : signingCredentials.Key.ToString(),
LogHelper.MarkAsNonPII(signingCredentials.Algorithm))));
try
{
if (LogHelper.IsEnabled(EventLogLevel.Verbose))
LogHelper.LogVerbose(LogMessages.IDX14200);
return signatureProvider.Sign(input, offset, count);
}
finally
{
cryptoProviderFactory.ReleaseSignatureProvider(signatureProvider);
}
}
#if NET6_0_OR_GREATER
/// <summary>
/// Produces a signature over the <paramref name="data"/>.
/// </summary>
/// <param name="data">Span containing bytes to be signed.</param>
/// <param name="destination">destination for signature.</param>
/// <param name="signingCredentials">The <see cref="SigningCredentials"/> that contain crypto specs used to sign the token.</param>
/// <param name="bytesWritten"></param>
/// <returns>The size of the signature.</returns>
/// <exception cref="ArgumentNullException">'input' or 'signingCredentials' is null.</exception>
internal static bool CreateSignature(
ReadOnlySpan<byte> data,
Span<byte> destination,
SigningCredentials signingCredentials,
out int bytesWritten)
{
bytesWritten = 0;
if (signingCredentials == null)
return false;
var cryptoProviderFactory = signingCredentials.CryptoProviderFactory ?? signingCredentials.Key.CryptoProviderFactory;
var signatureProvider = cryptoProviderFactory.CreateForSigning(signingCredentials.Key, signingCredentials.Algorithm) ??
throw LogHelper.LogExceptionMessage(
new InvalidOperationException(
LogHelper.FormatInvariant(
TokenLogMessages.IDX10637, signingCredentials.Key == null ? "Null" : signingCredentials.Key.ToString(),
LogHelper.MarkAsNonPII(signingCredentials.Algorithm))));
try
{
if (LogHelper.IsEnabled(EventLogLevel.Verbose))
LogHelper.LogVerbose(LogMessages.IDX14200);
return signatureProvider.Sign(data, destination, out bytesWritten);
}
finally
{
cryptoProviderFactory.ReleaseSignatureProvider(signatureProvider);
}
}
#endif
/// <summary>
/// Decompress JWT token bytes.
/// </summary>
/// <param name="tokenBytes"></param>
/// <param name="algorithm"></param>
/// <param name="maximumDeflateSize"></param>
/// <exception cref="ArgumentNullException">if <paramref name="tokenBytes"/> is null.</exception>
/// <exception cref="ArgumentNullException">if <paramref name="algorithm"/> is null.</exception>
/// <exception cref="NotSupportedException">if the decompression <paramref name="algorithm"/> is not supported.</exception>
/// <exception cref="SecurityTokenDecompressionFailedException">if decompression using <paramref name="algorithm"/> fails.</exception>
/// <returns>Decompressed JWT token</returns>
internal static string DecompressToken(byte[] tokenBytes, string algorithm, int maximumDeflateSize)
{
if (tokenBytes == null)
throw LogHelper.LogArgumentNullException(nameof(tokenBytes));
if (string.IsNullOrEmpty(algorithm))
throw LogHelper.LogArgumentNullException(nameof(algorithm));
if (!CompressionProviderFactory.Default.IsSupportedAlgorithm(algorithm))
throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10682, LogHelper.MarkAsNonPII(algorithm))));
var compressionProvider = CompressionProviderFactory.Default.CreateCompressionProvider(algorithm, maximumDeflateSize);
var decompressedBytes = compressionProvider.Decompress(tokenBytes);
return decompressedBytes != null ? Encoding.UTF8.GetString(decompressedBytes) : throw LogHelper.LogExceptionMessage(new SecurityTokenDecompressionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10679, LogHelper.MarkAsNonPII(algorithm))));
}
/// <summary>
/// Decrypts a Json Web Token.
/// </summary>
/// <param name="securityToken">The Json Web Token, could be a JwtSecurityToken or JsonWebToken</param>
/// <param name="validationParameters">The validation parameters containing cryptographic material.</param>
/// <param name="decryptionParameters">The decryption parameters container.</param>
/// <returns>The decrypted, and if the 'zip' claim is set, decompressed string representation of the token.</returns>
internal static string DecryptJwtToken(
SecurityToken securityToken,
TokenValidationParameters validationParameters,
JwtTokenDecryptionParameters decryptionParameters)
{
if (validationParameters == null)
throw LogHelper.LogArgumentNullException(nameof(validationParameters));
if (decryptionParameters == null)
throw LogHelper.LogArgumentNullException(nameof(decryptionParameters));
bool decryptionSucceeded = false;
bool algorithmNotSupportedByCryptoProvider = false;
byte[] decryptedTokenBytes = null;
// keep track of exceptions thrown, keys that were tried
StringBuilder exceptionStrings = null;
StringBuilder keysAttempted = null;
string zipAlgorithm = null;
foreach (SecurityKey key in decryptionParameters.Keys)
{
var cryptoProviderFactory = validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory;
if (cryptoProviderFactory == null)
{
if (LogHelper.IsEnabled(EventLogLevel.Warning))
LogHelper.LogWarning(TokenLogMessages.IDX10607, key);
continue;
}
try
{
// The JsonWebTokenHandler will set the JsonWebToken and those values will be used.
// The JwtSecurityTokenHandler will calculate values and set the values on DecrytionParameters.
// JsonWebToken from JsonWebTokenHandler
if (securityToken is JsonWebToken jsonWebToken)
{
if (!cryptoProviderFactory.IsSupportedAlgorithm(jsonWebToken.Enc, key))
{
if (LogHelper.IsEnabled(EventLogLevel.Warning))
LogHelper.LogWarning(TokenLogMessages.IDX10611, LogHelper.MarkAsNonPII(decryptionParameters.Enc), key);
algorithmNotSupportedByCryptoProvider = true;
continue;
}
Validators.ValidateAlgorithm(jsonWebToken.Enc, key, securityToken, validationParameters);
decryptedTokenBytes = DecryptToken(
cryptoProviderFactory,
key,
jsonWebToken.Enc,
jsonWebToken.CipherTextBytes,
jsonWebToken.HeaderAsciiBytes,
jsonWebToken.InitializationVectorBytes,
jsonWebToken.AuthenticationTagBytes);
zipAlgorithm = jsonWebToken.Zip;
decryptionSucceeded = true;
break;
}
// JwtSecurityToken from JwtSecurityTokenHandler
else
{
if (!cryptoProviderFactory.IsSupportedAlgorithm(decryptionParameters.Enc, key))
{
if (LogHelper.IsEnabled(EventLogLevel.Warning))
LogHelper.LogWarning(TokenLogMessages.IDX10611, LogHelper.MarkAsNonPII(decryptionParameters.Enc), key);
algorithmNotSupportedByCryptoProvider = true;
continue;
}
Validators.ValidateAlgorithm(decryptionParameters.Enc, key, securityToken, validationParameters);
decryptedTokenBytes = DecryptToken(
cryptoProviderFactory,
key,
decryptionParameters.Enc,
decryptionParameters.CipherTextBytes,
decryptionParameters.HeaderAsciiBytes,
decryptionParameters.InitializationVectorBytes,
decryptionParameters.AuthenticationTagBytes);
zipAlgorithm = decryptionParameters.Zip;
decryptionSucceeded = true;
break;
}
}
catch (Exception ex)
{
(exceptionStrings ??= new StringBuilder()).AppendLine(ex.ToString());
}
if (key != null)
(keysAttempted ??= new StringBuilder()).AppendLine(key.ToString());
}
ValidateDecryption(decryptionParameters, decryptionSucceeded, algorithmNotSupportedByCryptoProvider, exceptionStrings, keysAttempted);
try
{
if (string.IsNullOrEmpty(zipAlgorithm))
return Encoding.UTF8.GetString(decryptedTokenBytes);
return decryptionParameters.DecompressionFunction(decryptedTokenBytes, zipAlgorithm, decryptionParameters.MaximumDeflateSize);
}
catch (Exception ex)
{
throw LogHelper.LogExceptionMessage(new SecurityTokenDecompressionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10679, zipAlgorithm), ex));
}
}
private static void ValidateDecryption(JwtTokenDecryptionParameters decryptionParameters, bool decryptionSucceeded, bool algorithmNotSupportedByCryptoProvider, StringBuilder exceptionStrings, StringBuilder keysAttempted)
{
if (!decryptionSucceeded && keysAttempted is not null)
throw LogHelper.LogExceptionMessage(new SecurityTokenDecryptionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10603, keysAttempted, (object)exceptionStrings ?? "", LogHelper.MarkAsSecurityArtifact(decryptionParameters.EncodedToken, SafeLogJwtToken))));
if (!decryptionSucceeded && algorithmNotSupportedByCryptoProvider)
throw LogHelper.LogExceptionMessage(new SecurityTokenDecryptionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10619, LogHelper.MarkAsNonPII(decryptionParameters.Alg), LogHelper.MarkAsNonPII(decryptionParameters.Enc))));
if (!decryptionSucceeded)
throw LogHelper.LogExceptionMessage(new SecurityTokenDecryptionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10609, LogHelper.MarkAsSecurityArtifact(decryptionParameters.EncodedToken, SafeLogJwtToken))));
}
private static byte[] DecryptToken(CryptoProviderFactory cryptoProviderFactory, SecurityKey key, string encAlg, byte[] ciphertext, byte[] headerAscii, byte[] initializationVector, byte[] authenticationTag)
{
using (AuthenticatedEncryptionProvider decryptionProvider = cryptoProviderFactory.CreateAuthenticatedEncryptionProvider(key, encAlg))
{
if (decryptionProvider == null)
throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(TokenLogMessages.IDX10610, key, LogHelper.MarkAsNonPII(encAlg))));
return decryptionProvider.Decrypt(
ciphertext,
headerAscii,
initializationVector,
authenticationTag);
}
}
/// <summary>
/// Generates key bytes.
/// </summary>
public static byte[] GenerateKeyBytes(int sizeInBits)
{
byte[] key = null;
if (sizeInBits != 256 && sizeInBits != 384 && sizeInBits != 512)
throw LogHelper.LogExceptionMessage(new ArgumentException(TokenLogMessages.IDX10401, nameof(sizeInBits)));
using (var aes = Aes.Create())
{
int halfSizeInBytes = sizeInBits >> 4;
key = new byte[halfSizeInBytes << 1];
aes.KeySize = sizeInBits >> 1;
// The design of AuthenticatedEncryption needs two keys of the same size - generate them, each half size of what's required
aes.GenerateKey();
Array.Copy(aes.Key, key, halfSizeInBytes);
aes.GenerateKey();
Array.Copy(aes.Key, 0, key, halfSizeInBytes, halfSizeInBytes);
}
return key;
}
internal static SecurityKey GetSecurityKey(
EncryptingCredentials encryptingCredentials,
CryptoProviderFactory cryptoProviderFactory,
IDictionary<string, object> additionalHeaderClaims,
out byte[] wrappedKey)
{
SecurityKey securityKey = null;
wrappedKey = null;
// if direct algorithm, look for support
if (JwtConstants.DirectKeyUseAlg.Equals(encryptingCredentials.Alg))
{
if (!cryptoProviderFactory.IsSupportedAlgorithm(encryptingCredentials.Enc, encryptingCredentials.Key))
throw LogHelper.LogExceptionMessage(new SecurityTokenEncryptionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10615, LogHelper.MarkAsNonPII(encryptingCredentials.Enc), encryptingCredentials.Key)));
securityKey = encryptingCredentials.Key;
}
#if NET472 || NET6_0_OR_GREATER
else if (SupportedAlgorithms.EcdsaWrapAlgorithms.Contains(encryptingCredentials.Alg))
{
// on decryption we get the public key from the EPK value see: https://datatracker.ietf.org/doc/html/rfc7518#appendix-C
string apu = null, apv = null;
if (additionalHeaderClaims != null && additionalHeaderClaims.Count > 0)
{
if (additionalHeaderClaims.TryGetValue(JwtHeaderParameterNames.Apu, out object objApu))
apu = objApu?.ToString();
if (additionalHeaderClaims.TryGetValue(JwtHeaderParameterNames.Apv, out object objApv))
apv = objApv?.ToString();
}
EcdhKeyExchangeProvider ecdhKeyExchangeProvider = new EcdhKeyExchangeProvider(encryptingCredentials.Key as ECDsaSecurityKey, encryptingCredentials.KeyExchangePublicKey, encryptingCredentials.Alg, encryptingCredentials.Enc);
SecurityKey kdf = ecdhKeyExchangeProvider.GenerateKdf(apu, apv);
using KeyWrapProvider kwProvider = cryptoProviderFactory.CreateKeyWrapProvider(kdf, ecdhKeyExchangeProvider.GetEncryptionAlgorithm());
// only 128, 384 and 512 AesKeyWrap for CEK algorithm
if (SecurityAlgorithms.Aes128KW.Equals(kwProvider.Algorithm, StringComparison.Ordinal))
securityKey = new SymmetricSecurityKey(GenerateKeyBytes(256));
else if (SecurityAlgorithms.Aes192KW.Equals(kwProvider.Algorithm, StringComparison.Ordinal))
securityKey = new SymmetricSecurityKey(GenerateKeyBytes(384));
else if (SecurityAlgorithms.Aes256KW.Equals(kwProvider.Algorithm, StringComparison.Ordinal))
securityKey = new SymmetricSecurityKey(GenerateKeyBytes(512));
else
throw LogHelper.LogExceptionMessage(
new SecurityTokenEncryptionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10617, LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes128KW), LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes192KW), LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes256KW), LogHelper.MarkAsNonPII(kwProvider.Algorithm))));
wrappedKey = kwProvider.WrapKey(((SymmetricSecurityKey)securityKey).Key);
}
#endif
else
{
if (!cryptoProviderFactory.IsSupportedAlgorithm(encryptingCredentials.Alg, encryptingCredentials.Key))
throw LogHelper.LogExceptionMessage(new SecurityTokenEncryptionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10615, LogHelper.MarkAsNonPII(encryptingCredentials.Alg), encryptingCredentials.Key)));
// only 128, 384 and 512 AesCbcHmac for CEK algorithm
if (SecurityAlgorithms.Aes128CbcHmacSha256.Equals(encryptingCredentials.Enc))
securityKey = new SymmetricSecurityKey(GenerateKeyBytes(256));
else if (SecurityAlgorithms.Aes192CbcHmacSha384.Equals(encryptingCredentials.Enc))
securityKey = new SymmetricSecurityKey(GenerateKeyBytes(384));
else if (SecurityAlgorithms.Aes256CbcHmacSha512.Equals(encryptingCredentials.Enc))
securityKey = new SymmetricSecurityKey(GenerateKeyBytes(512));
else
throw LogHelper.LogExceptionMessage(
new SecurityTokenEncryptionFailedException(LogHelper.FormatInvariant(TokenLogMessages.IDX10617, LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes128CbcHmacSha256), LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes192CbcHmacSha384), LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes256CbcHmacSha512), LogHelper.MarkAsNonPII(encryptingCredentials.Enc))));
using KeyWrapProvider kwProvider = cryptoProviderFactory.CreateKeyWrapProvider(encryptingCredentials.Key, encryptingCredentials.Alg);
wrappedKey = kwProvider.WrapKey(((SymmetricSecurityKey)securityKey).Key);
}
return securityKey;
}
/// <summary>
/// Gets all decryption keys.
/// </summary>
public static IEnumerable<SecurityKey> GetAllDecryptionKeys(TokenValidationParameters validationParameters)
{
if (validationParameters == null)
throw new ArgumentNullException(nameof(validationParameters));
var decryptionKeys = new Collection<SecurityKey>();
if (validationParameters.TokenDecryptionKey != null)
decryptionKeys.Add(validationParameters.TokenDecryptionKey);
if (validationParameters.TokenDecryptionKeys != null)
foreach (SecurityKey key in validationParameters.TokenDecryptionKeys)
decryptionKeys.Add(key);
return decryptionKeys;
}
internal static string SafeLogJwtToken(object obj)
{
if (obj == null)
return string.Empty;
// not a string, we do not know how to sanitize so we return a String which represents the object instance
if (!(obj is string token))
return obj.GetType().ToString();
int lastDot = token.LastIndexOf(".");
// no dots, not a JWT, we do not know how to sanitize so we return UnrecognizedEncodedToken
if (lastDot == -1)
return _unrecognizedEncodedToken;
return token.Substring(0, lastDot);
}
/// <summary>
/// Returns a <see cref="SecurityKey"/> to use when validating the signature of a token.
/// </summary>
/// <param name="kid">The <see cref="string"/> kid field of the token being validated</param>
/// <param name="x5t">The <see cref="string"/> x5t field of the token being validated</param>
/// <param name="validationParameters">A <see cref="TokenValidationParameters"/> required for validation.</param>
/// <param name="configuration">The <see cref="BaseConfiguration"/> that will be used along with the <see cref="TokenValidationParameters"/> to resolve the signing key</param>
/// <returns>Returns a <see cref="SecurityKey"/> to use for signature validation.</returns>
/// <remarks>Resolve the signing key using configuration then the validationParameters until a key is resolved. If key fails to resolve, then null is returned.</remarks>
internal static SecurityKey ResolveTokenSigningKey(string kid, string x5t, TokenValidationParameters validationParameters, BaseConfiguration configuration)
{
return ResolveTokenSigningKey(kid, x5t, configuration?.SigningKeys) ?? ResolveTokenSigningKey(kid, x5t, ConcatSigningKeys(validationParameters));
}
/// <summary>
/// Returns a <see cref="SecurityKey"/> to use when validating the signature of a token.
/// </summary>
/// <param name="kid">The <see cref="string"/> kid field of the token being validated</param>
/// <param name="x5t">The <see cref="string"/> x5t field of the token being validated</param>
/// <param name="signingKeys">A collection of <see cref="SecurityKey"/> a signing key to be resolved from.</param>
/// <returns>Returns a <see cref="SecurityKey"/> to use for signature validation.</returns>
/// <remarks>If key fails to resolve, then null is returned</remarks>
internal static SecurityKey ResolveTokenSigningKey(string kid, string x5t, IEnumerable<SecurityKey> signingKeys)
{
if (signingKeys == null)
return null;
foreach (SecurityKey signingKey in signingKeys)
{
if (signingKey != null)
{
if (signingKey is X509SecurityKey x509Key)
{
if ((!string.IsNullOrEmpty(kid) && string.Equals(signingKey.KeyId, kid, StringComparison.OrdinalIgnoreCase)) ||
(!string.IsNullOrEmpty(x5t) && string.Equals(x509Key.X5t, x5t, StringComparison.OrdinalIgnoreCase)))
{
return signingKey;
}
}
else if (!string.IsNullOrEmpty(signingKey.KeyId))
{
if (string.Equals(signingKey.KeyId, kid) || string.Equals(signingKey.KeyId, x5t))
{
return signingKey;
}
}
}
}
return null;
}
/// <summary>
/// Counts the number of Jwt Token segments.
/// </summary>
/// <param name="token">The Jwt Token.</param>
/// <param name="maxCount">The maximum number of segments to count up to.</param>
/// <returns>The number of segments up to <paramref name="maxCount"/>.</returns>
internal static int CountJwtTokenPart(string token, int maxCount)
{
var count = 1;
var index = 0;
while (index < token.Length)
{
var dotIndex = token.IndexOf('.', index);
if (dotIndex < 0)
{
break;
}
count++;
index = dotIndex + 1;
if (count == maxCount)
{
break;
}
}
return count;
}
internal static IEnumerable<SecurityKey> ConcatSigningKeys(TokenValidationParameters tvp)
{
if (tvp == null)
yield break;
yield return tvp.IssuerSigningKey;
if (tvp.IssuerSigningKeys != null)
{
foreach (var key in tvp.IssuerSigningKeys)
{
yield return key;
}
}
}
// If a string is in IS8061 format, assume a DateTime is in UTC
// Because this is a friend class, we can't remove this method without
// breaking compatibility.
internal static string GetStringClaimValueType(string str)
{
return GetStringClaimValueType(str, string.Empty);
}
internal static string GetStringClaimValueType(string str, string claimType)
{
if (!string.IsNullOrEmpty(claimType) && !JsonSerializerPrimitives.TryAllStringClaimsAsDateTime() && JsonSerializerPrimitives.IsKnownToNotBeDateTime(claimType))
return ClaimValueTypes.String;
if (DateTime.TryParse(str, out DateTime dateTimeValue))
{
string dtUniversal = dateTimeValue.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture);
if (dtUniversal.Equals(str, StringComparison.Ordinal))
return ClaimValueTypes.DateTime;
}
return ClaimValueTypes.String;
}
}
}