-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathJsonWebTokenHandler.ValidateToken.Internal.cs
More file actions
374 lines (318 loc) · 16.9 KB
/
JsonWebTokenHandler.ValidateToken.Internal.cs
File metadata and controls
374 lines (318 loc) · 16.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
#nullable enable
namespace Microsoft.IdentityModel.JsonWebTokens
{
public partial class JsonWebTokenHandler : TokenHandler
{
/// <inheritdoc/>
public override async Task<ValidationResult<ValidatedToken, ValidationError>> ValidateTokenAsync(
string token,
ValidationParameters validationParameters,
CallContext callContext,
CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(token))
{
return ValidationError.NullParameter(
nameof(token),
ValidationError.GetCurrentStackFrame());
}
if (validationParameters is null)
{
return ValidationError.NullParameter(
nameof(validationParameters),
ValidationError.GetCurrentStackFrame());
}
if (token.Length > MaximumTokenSizeInBytes)
{
return new ValidationError(
new MessageDetail(
TokenLogMessages.IDX10209,
LogHelper.MarkAsNonPII(token.Length),
LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes)),
ValidationFailureType.SecurityTokenTooLarge,
ValidationError.GetCurrentStackFrame());
}
ValidationResult<SecurityToken, ValidationError> readResult = ReadToken(token, callContext);
if (readResult.Succeeded)
{
ValidationResult<ValidatedToken, ValidationError> validationResult = await ValidateTokenAsync(
readResult.Result!,
validationParameters,
callContext,
cancellationToken)
.ConfigureAwait(false);
if (validationResult.Succeeded)
return validationResult; // No need to unwrap and re-wrap the result.
return validationResult.Error!.AddStackFrame(ValidationError.GetCurrentStackFrame());
}
return readResult.Error!.AddCurrentStackFrame();
}
/// <inheritdoc/>
public override async Task<ValidationResult<ValidatedToken, ValidationError>> ValidateTokenAsync(
SecurityToken token,
ValidationParameters validationParameters,
CallContext callContext,
CancellationToken cancellationToken)
{
if (token is null)
{
return ValidationError.NullParameter(
nameof(token),
ValidationError.GetCurrentStackFrame());
}
if (validationParameters is null)
{
return ValidationError.NullParameter(
nameof(validationParameters),
ValidationError.GetCurrentStackFrame());
}
if (token is not JsonWebToken jsonWebToken)
{
return new ValidationError(
new MessageDetail(TokenLogMessages.IDX10001, nameof(token), nameof(JsonWebToken)),
ValidationFailureType.SecurityTokenNotExpectedType,
ValidationError.GetCurrentStackFrame());
}
BaseConfiguration? currentConfiguration =
await GetCurrentConfigurationAsync(validationParameters, cancellationToken).ConfigureAwait(false);
ValidationResult<ValidatedToken, ValidationError> result = jsonWebToken.IsEncrypted ?
await ValidateJWEAsync(jsonWebToken, validationParameters, currentConfiguration, callContext, cancellationToken).ConfigureAwait(false) :
await ValidateJWSAsync(jsonWebToken, validationParameters, currentConfiguration, callContext, cancellationToken).ConfigureAwait(false);
if (validationParameters.ConfigurationManager is null)
{
if (result.Succeeded)
return result;
return result.Error!.AddStackFrame(ValidationError.GetCurrentStackFrame());
}
if (result.Succeeded)
{
// Set current configuration as LKG if it exists.
if (currentConfiguration is not null)
validationParameters.ConfigurationManager.LastKnownGoodConfiguration = currentConfiguration;
return result;
}
if (TokenUtilities.IsRecoverableFailureType(result.Error!.FailureType, (currentConfiguration != null && currentConfiguration.TokenDecryptionKeys.Count > 0)))
{
// 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 is not null)
{
validationParameters.ConfigurationManager.RequestRefresh();
validationParameters.RefreshBeforeValidation = true;
BaseConfiguration lastConfig = currentConfiguration;
currentConfiguration = await validationParameters.ConfigurationManager.GetBaseConfigurationAsync(CancellationToken.None).ConfigureAwait(false);
// Only try to re-validate using the newly obtained config if it doesn't reference equal the previously used configuration.
if (lastConfig != currentConfiguration)
{
result = jsonWebToken.IsEncrypted ?
await ValidateJWEAsync(jsonWebToken, validationParameters, currentConfiguration, callContext, cancellationToken).ConfigureAwait(false) :
await ValidateJWSAsync(jsonWebToken, validationParameters, currentConfiguration, callContext, cancellationToken).ConfigureAwait(false);
if (result.Succeeded)
{
validationParameters.ConfigurationManager.LastKnownGoodConfiguration = currentConfiguration;
return result;
}
}
}
if (validationParameters.ConfigurationManager.UseLastKnownGoodConfiguration)
{
validationParameters.RefreshBeforeValidation = false;
validationParameters.ValidateWithLKG = true;
ValidationFailureType failureType = result.Error!.FailureType;
BaseConfiguration[] validConfigurations = validationParameters.ConfigurationManager.GetValidLkgConfigurations();
for (int i = 0; i < validConfigurations.Length; i++)
{
BaseConfiguration lkgConfiguration = validConfigurations[i];
if (TokenUtilities.IsRecoverableConfigurationAndExceptionType(
jsonWebToken.Kid, currentConfiguration, lkgConfiguration, failureType))
{
result = jsonWebToken.IsEncrypted ?
await ValidateJWEAsync(jsonWebToken, validationParameters, lkgConfiguration, callContext, cancellationToken).ConfigureAwait(false) :
await ValidateJWSAsync(jsonWebToken, validationParameters, lkgConfiguration, callContext, cancellationToken).ConfigureAwait(false);
if (result.Succeeded)
return result;
}
}
}
}
// If we reach this point, the token validation failed and we should return the error.
return result.Error!.AddCurrentStackFrame();
}
private async ValueTask<ValidationResult<ValidatedToken, ValidationError>> ValidateJWEAsync(
JsonWebToken jwtToken,
ValidationParameters validationParameters,
BaseConfiguration? configuration,
CallContext callContext,
CancellationToken cancellationToken)
{
ValidationResult<string, ValidationError> decryptionResult = DecryptToken(
jwtToken, validationParameters, configuration, callContext);
if (!decryptionResult.Succeeded)
{
return decryptionResult.Error!.AddCurrentStackFrame();
}
ValidationResult<SecurityToken, ValidationError> readResult = ReadToken(decryptionResult.Result!, callContext);
if (!readResult.Succeeded)
{
return readResult.Error!.AddCurrentStackFrame();
}
JsonWebToken decryptedToken = (readResult.Result as JsonWebToken)!;
ValidationResult<ValidatedToken, ValidationError> validationResult =
await ValidateJWSAsync(decryptedToken!, validationParameters, configuration, callContext, cancellationToken)
.ConfigureAwait(false);
if (!validationResult.Succeeded)
{
return validationResult.Error!.AddCurrentStackFrame();
}
JsonWebToken jsonWebToken = (validationResult.Result!.SecurityToken as JsonWebToken)!;
jwtToken.InnerToken = jsonWebToken;
jwtToken.Payload = jsonWebToken.Payload;
return validationResult;
}
private async ValueTask<ValidationResult<ValidatedToken, ValidationError>> ValidateJWSAsync(
JsonWebToken jsonWebToken,
ValidationParameters validationParameters,
BaseConfiguration? configuration,
CallContext callContext,
CancellationToken cancellationToken)
{
DateTime? expires = jsonWebToken.HasPayloadClaim(JwtRegisteredClaimNames.Exp) ? jsonWebToken.ValidTo : null;
DateTime? notBefore = jsonWebToken.HasPayloadClaim(JwtRegisteredClaimNames.Nbf) ? jsonWebToken.ValidFrom : null;
ValidationResult<ValidatedLifetime, ValidationError> lifetimeResult =
Validators.ValidateLifetimeInternal(
notBefore,
expires,
jsonWebToken,
validationParameters,
callContext);
if (!lifetimeResult.Succeeded)
return lifetimeResult.Error!.AddCurrentStackFrame();
if (jsonWebToken.Audiences is not IList<string> tokenAudiences)
tokenAudiences = [.. jsonWebToken.Audiences];
ValidationResult<string, ValidationError> audienceResult =
Validators.ValidateAudienceInternal(
tokenAudiences,
jsonWebToken,
validationParameters,
callContext);
if (!audienceResult.Succeeded)
return audienceResult.Error!.AddCurrentStackFrame();
ValidationResult<ValidatedIssuer, ValidationError> issuerResult =
await Validators.ValidateIssuerInternalAsync(
jsonWebToken.Issuer,
jsonWebToken,
validationParameters,
callContext,
cancellationToken).ConfigureAwait(false);
if (!issuerResult.Succeeded)
return issuerResult.Error!.AddCurrentStackFrame();
ValidationResult<DateTime?, ValidationError>? tokenReplayResult =
Validators.ValidateTokenReplayInternal(
expires,
jsonWebToken.EncodedToken,
validationParameters,
callContext);
if (!tokenReplayResult.Value.Succeeded)
return tokenReplayResult.Value.Error!.AddCurrentStackFrame();
ValidationResult<ValidatedTokenType, ValidationError> tokenTypeResult =
Validators.ValidateTokenTypeInternal(
jsonWebToken.Typ,
jsonWebToken,
validationParameters,
callContext);
if (!tokenTypeResult.Succeeded)
return tokenTypeResult.Error!.AddCurrentStackFrame();
ValidationResult<string, ValidationError> algorithmResult =
Validators.ValidateAlgorithmInternal(
jsonWebToken.Alg,
jsonWebToken,
validationParameters,
callContext);
if (!algorithmResult.Succeeded)
return algorithmResult.Error!.AddCurrentStackFrame();
// The signature validation delegate is yet to be migrated to ValidationParameters.
ValidationResult<SecurityKey, ValidationError> signatureResult =
ValidateSignature(
jsonWebToken,
validationParameters,
configuration,
callContext);
if (!signatureResult.Succeeded)
return signatureResult.Error!.AddCurrentStackFrame();
ValidationResult<ValidatedSignatureKey, ValidationError> signatureKeyResult =
Validators.ValidateSignatureKeyInternal(
jsonWebToken.SigningKey,
jsonWebToken,
validationParameters,
callContext);
if (!signatureKeyResult.Succeeded)
return signatureKeyResult.Error!.AddCurrentStackFrame();
// actor validation
ValidationResult<ValidatedToken, ValidationError>? actorResult = null;
if (validationParameters.ValidateActor && !string.IsNullOrWhiteSpace(jsonWebToken.Actor))
{
ValidationResult<SecurityToken, ValidationError> readResult = ReadToken(jsonWebToken.Actor, callContext);
if (!readResult.Succeeded)
return readResult.Error!.AddCurrentStackFrame();
if (validationParameters.ActorValidationParameters is null)
return ValidationError.NullParameter(
nameof(validationParameters.ActorValidationParameters),
ValidationError.GetCurrentStackFrame());
// TODO - what if actor token is encrypted?
JsonWebToken actorToken = (readResult.Result as JsonWebToken)!;
actorResult = await ValidateJWSAsync(
actorToken,
validationParameters.ActorValidationParameters,
configuration,
callContext,
cancellationToken).ConfigureAwait(false);
if (!actorResult.Value.Succeeded)
return actorResult.Value.Error!.AddCurrentStackFrame();
}
return new ValidatedToken(jsonWebToken, this, validationParameters)
{
ValidatedLifetime = lifetimeResult.Result,
ValidatedAlgorithm = algorithmResult.Result,
ValidatedAudience = audienceResult.Result,
ValidatedIssuer = issuerResult.Result,
ActorValidationResult = actorResult?.Result,
ValidatedTokenType = tokenTypeResult.Result,
ValidatedSignatureKey = signatureResult.Result
};
}
private static async Task<BaseConfiguration?> GetCurrentConfigurationAsync(ValidationParameters validationParameters, CancellationToken cancellationToken)
{
BaseConfiguration? currentConfiguration = null;
if (validationParameters.ConfigurationManager is not null)
{
try
{
currentConfiguration = await validationParameters.ConfigurationManager.GetBaseConfigurationAsync(cancellationToken).ConfigureAwait(false);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch
#pragma warning restore CA1031 // Do not catch general exception types
{
// The exception is tracked and dismissed as the ValidationParameters may have the issuer
// and signing key set directly on them, allowing the library to continue with token validation.
// TODO: Move to CallContext.
//if (LogHelper.IsEnabled(EventLogLevel.Warning))
// LogHelper.LogWarning(LogHelper.FormatInvariant(TokenLogMessages.IDX10261, validationParameters.ConfigurationManager.MetadataAddress, ex.ToString()));
}
}
return currentConfiguration;
}
}
}
#nullable restore