-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathJsonWebTokenHandler.ValidateSignature.cs
More file actions
350 lines (319 loc) · 15.9 KB
/
JsonWebTokenHandler.ValidateSignature.cs
File metadata and controls
350 lines (319 loc) · 15.9 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens.Experimental;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
#nullable enable
namespace Microsoft.IdentityModel.JsonWebTokens
{
/// <remarks>This partial class contains methods and logic related to the validation of tokens' signatures.</remarks>
public partial class JsonWebTokenHandler : TokenHandler
{
/// <summary>
/// Validates the JWT signature.
/// </summary>
/// <param name="jwtToken">The JWT token to validate.</param>
/// <param name="validationParameters">The parameters used for validation.</param>
/// <param name="configuration">The optional configuration used for validation.</param>
/// <param name="callContext">The context in which the method is called.</param>
/// <returns>A <see cref="ValidationResult{SecurityKey, ValidationError}"/> with the <see cref="SecurityKey"/> that signed the tokenif valid or a <see cref="ValidationError"/>.</returns>
internal static ValidationResult<SecurityKey, ValidationError> ValidateSignature(
JsonWebToken jwtToken,
ValidationParameters validationParameters,
BaseConfiguration? configuration,
CallContext callContext)
{
if (jwtToken is null)
return ValidationError.NullParameter(
nameof(jwtToken),
ValidationError.GetCurrentStackFrame());
if (validationParameters is null)
return ValidationError.NullParameter(
nameof(validationParameters),
ValidationError.GetCurrentStackFrame());
// Delegate is set by the user, we call it and return the result.
if (validationParameters.SignatureValidator is not null)
{
try
{
ValidationResult<SecurityKey, ValidationError> signatureValidationResult =
validationParameters.SignatureValidator(
jwtToken,
validationParameters,
configuration,
callContext);
return signatureValidationResult;
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
return new SignatureValidationError(
new MessageDetail(TokenLogMessages.IDX10272),
SignatureValidationFailure.ValidatorThrew,
ValidationError.GetCurrentStackFrame(),
ex);
}
}
// If the user wants to accept unsigned tokens, they must implement the delegate.
if (!jwtToken.IsSigned)
return new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10504,
LogHelper.MarkAsSecurityArtifact(
jwtToken.EncodedToken,
JwtTokenUtilities.SafeLogJwtToken)),
SignatureValidationFailure.TokenIsNotSigned,
ValidationError.GetCurrentStackFrame());
SecurityKey? key = null;
if (validationParameters.SignatureKeyResolver is not null)
{
key = validationParameters.SignatureKeyResolver(
jwtToken.EncodedToken,
jwtToken,
jwtToken.Kid,
validationParameters,
configuration,
callContext);
}
else
{
// Resolve the key using the token's 'kid' and 'x5t' headers.
// Fall back to the validation parameters' keys if configuration keys are not set.
key = JwtTokenUtilities.ResolveTokenSigningKey(jwtToken.Kid, jwtToken.X5t, configuration?.SigningKeys)
?? JwtTokenUtilities.ResolveTokenSigningKey(jwtToken.Kid, jwtToken.X5t, validationParameters.SigningKeys);
}
if (key is not null)
return ValidateSignatureWithKey(jwtToken, validationParameters, key, callContext);
if (validationParameters.TryAllSigningKeys)
return ValidateSignatureUsingAllKeys(jwtToken, validationParameters, configuration, callContext);
// kid was NOT found, no matching keys available.
if (string.IsNullOrEmpty(jwtToken.Kid))
{
return new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10526,
LogHelper.MarkAsNonPII(validationParameters.SigningKeys.Count),
LogHelper.MarkAsNonPII(configuration?.SigningKeys?.Count ?? 0),
LogHelper.MarkAsSecurityArtifact(jwtToken.EncodedToken, JwtTokenUtilities.SafeLogJwtToken)),
SignatureValidationFailure.SigningKeyNotFound,
ValidationError.GetCurrentStackFrame());
}
// kid was found, no matching keys available.
return new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10527,
LogHelper.MarkAsNonPII(jwtToken.Kid),
LogHelper.MarkAsNonPII(validationParameters.SigningKeys.Count),
LogHelper.MarkAsNonPII(configuration?.SigningKeys?.Count ?? 0),
LogHelper.MarkAsSecurityArtifact(jwtToken.EncodedToken, JwtTokenUtilities.SafeLogJwtToken)),
SignatureValidationFailure.SigningKeyNotFound,
ValidationError.GetCurrentStackFrame());
}
private static ValidationResult<SecurityKey, ValidationError> ValidateSignatureUsingAllKeys(
JsonWebToken jwtToken,
ValidationParameters validationParameters,
BaseConfiguration? configuration,
CallContext callContext)
{
bool keysTried = false;
bool kidExists = !string.IsNullOrEmpty(jwtToken.Kid);
IEnumerable<SecurityKey>? keys = TokenUtilities.GetAllSigningKeys(configuration, validationParameters, callContext);
StringBuilder? exceptionStrings = null;
StringBuilder? keysAttempted = null;
// We want to capture all stack frames that were involved with faults.
// We capture the stack frames and add to the error.
IList<StackFrame>? stackFrames = null;
foreach (SecurityKey key in keys)
{
if (key is null)
continue;
keysTried = true;
// Validate the signature with each key.
ValidationResult<SecurityKey, ValidationError> result = ValidateSignatureWithKey(
jwtToken,
validationParameters,
key,
callContext);
if (result.Succeeded)
{
jwtToken.SigningKey = key;
return result;
}
if (result.Error is ValidationError validationError)
{
stackFrames ??= [];
foreach (StackFrame stackFrame in validationError.StackFrames)
stackFrames.Add(stackFrame);
exceptionStrings ??= new StringBuilder();
keysAttempted ??= new StringBuilder();
exceptionStrings.AppendLine(validationError.MessageDetail.Message);
keysAttempted.AppendLine(key.ToString());
}
}
// This method tries a number of different keys, for each failure we add a stack frame to the stackFrames collection.
// We want to add the current stack frame to the end of the list, to keep the order of the stack frames.
// If for some reason stackFrames is null or empty, we add the current stack frame as the first and only entry.
StackFrame currentStackFrame = ValidationError.GetCurrentStackFrame();
StackFrame firstStackFrame = (stackFrames == null || stackFrames.Count == 0) ? currentStackFrame : stackFrames[0];
SignatureValidationError signatureValidationError;
if (keysTried)
{
if (kidExists)
{
signatureValidationError = new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10522,
LogHelper.MarkAsNonPII(jwtToken.Kid),
LogHelper.MarkAsNonPII(validationParameters.SigningKeys.Count),
LogHelper.MarkAsNonPII(configuration?.SigningKeys?.Count ?? 0),
LogHelper.MarkAsSecurityArtifact(jwtToken.EncodedToken, JwtTokenUtilities.SafeLogJwtToken)),
SignatureValidationFailure.SigningKeyNotFound,
firstStackFrame);
}
else
{
signatureValidationError = new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10523,
LogHelper.MarkAsNonPII(validationParameters.SigningKeys.Count),
LogHelper.MarkAsNonPII(configuration?.SigningKeys?.Count ?? 0),
LogHelper.MarkAsSecurityArtifact(jwtToken.EncodedToken, JwtTokenUtilities.SafeLogJwtToken)),
SignatureValidationFailure.SigningKeyNotFound,
firstStackFrame);
}
}
else if (kidExists)
{
// There is a kid, but no keys were found.
signatureValidationError = new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10524,
LogHelper.MarkAsNonPII(jwtToken.Kid),
LogHelper.MarkAsNonPII(validationParameters.SigningKeys.Count),
LogHelper.MarkAsNonPII(configuration?.SigningKeys?.Count ?? 0),
LogHelper.MarkAsSecurityArtifact(jwtToken.EncodedToken, JwtTokenUtilities.SafeLogJwtToken)),
SignatureValidationFailure.SigningKeyNotFound,
firstStackFrame);
}
else
{
signatureValidationError = new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10525,
LogHelper.MarkAsNonPII(validationParameters.SigningKeys.Count),
LogHelper.MarkAsNonPII(configuration?.SigningKeys?.Count ?? 0),
LogHelper.MarkAsSecurityArtifact(jwtToken.EncodedToken, JwtTokenUtilities.SafeLogJwtToken)),
SignatureValidationFailure.SigningKeyNotFound,
firstStackFrame);
}
if (stackFrames != null)
{
for (int i = 1; i < stackFrames.Count; i++)
{
if (stackFrames[i] != null)
signatureValidationError.StackFrames.Add(stackFrames[i]);
}
signatureValidationError.StackFrames.Add(currentStackFrame);
}
return signatureValidationError;
}
private static ValidationResult<SecurityKey, ValidationError> ValidateSignatureWithKey(
JsonWebToken jsonWebToken,
ValidationParameters validationParameters,
SecurityKey key,
#pragma warning disable CA1801 // Review unused parameters
CallContext callContext)
#pragma warning restore CA1801 // Review unused parameters
{
CryptoProviderFactory cryptoProviderFactory = validationParameters.CryptoProviderFactory ?? key.CryptoProviderFactory;
if (!cryptoProviderFactory.IsSupportedAlgorithm(jsonWebToken.Alg, key))
{
return new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10652,
LogHelper.MarkAsNonPII(jsonWebToken.Alg),
key),
AlgorithmValidationFailure.NotSupported,
ValidationError.GetCurrentStackFrame());
}
SignatureProvider signatureProvider = cryptoProviderFactory.CreateForVerifying(key, jsonWebToken.Alg);
try
{
if (signatureProvider == null)
return new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10636,
LogHelper.MarkAsNonPII(key?.KeyId ?? "Null"),
LogHelper.MarkAsNonPII(jsonWebToken.Alg)),
ValidationFailureType.CryptoProviderReturnedNull,
ValidationError.GetCurrentStackFrame());
bool valid = EncodingUtils.PerformEncodingDependentOperation<bool, string, int, SignatureProvider>(
jsonWebToken.EncodedToken,
0,
jsonWebToken.Dot2,
Encoding.UTF8,
jsonWebToken.EncodedToken,
jsonWebToken.Dot2,
signatureProvider,
ValidateSignature);
if (valid)
{
jsonWebToken.SigningKey = key;
return key;
}
else
return new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10520,
LogHelper.MarkAsNonPII(key.ToString())),
SignatureValidationFailure.ValidationFailed,
ValidationError.GetCurrentStackFrame());
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
return new SignatureValidationError(
new MessageDetail(
TokenLogMessages.IDX10521,
LogHelper.MarkAsNonPII(key.ToString()),
LogHelper.MarkAsNonPII(ex.Message)),
SignatureValidationFailure.ValidationFailed,
ValidationError.GetCurrentStackFrame(),
ex);
}
finally
{
cryptoProviderFactory.ReleaseSignatureProvider(signatureProvider);
}
}
private static void PopulateFailedResults(
KeyMatchFailedResult? failedResult,
StringBuilder exceptionStrings,
StringBuilder keysAttempted)
{
if (failedResult is KeyMatchFailedResult result)
{
for (int i = 0; i < result.KeysAttempted.Count; i++)
{
exceptionStrings.AppendLine(result.FailedResults[i].MessageDetail.Message);
keysAttempted.AppendLine(result.KeysAttempted[i].ToString());
}
}
}
private struct KeyMatchFailedResult(
IList<ValidationError> failedResults,
IList<SecurityKey> keysAttempted)
{
public IList<ValidationError> FailedResults = failedResults;
public IList<SecurityKey> KeysAttempted = keysAttempted;
}
}
}
#nullable restore