-
Notifications
You must be signed in to change notification settings - Fork 471
Expand file tree
/
Copy pathJsonClaimSet.cs
More file actions
437 lines (385 loc) · 18.8 KB
/
Copy pathJsonClaimSet.cs
File metadata and controls
437 lines (385 loc) · 18.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Security.Claims;
using System.Text.Json;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.Tokens.Json;
namespace Microsoft.IdentityModel.JsonWebTokens
{
/// <summary>
/// This class provides an abstraction over the json parser for net461+ using System.Text.Json.
/// <see cref="JsonWebToken"/> will delegate to this class to get values.
/// </summary>
internal class JsonClaimSet
{
internal const string ClassName = "Microsoft.IdentityModel.JsonWebTokens.JsonClaimSet";
internal object _claimsLock = new();
internal readonly Dictionary<string, object> _jsonClaims;
private List<Claim> _claims;
internal JsonClaimSet()
{
_jsonClaims = [];
}
internal JsonClaimSet(Dictionary<string, object> jsonClaims)
{
_jsonClaims = jsonClaims;
}
internal List<Claim> Claims(string issuer)
{
if (_claims == null)
lock (_claimsLock)
_claims ??= CreateClaims(issuer);
return _claims;
}
internal List<Claim> CreateClaims(string issuer)
{
var claims = new List<Claim>(_jsonClaims.Count);
foreach (KeyValuePair<string, object> kvp in _jsonClaims)
CreateClaimFromObject(claims, kvp.Key, kvp.Value, issuer);
return claims;
}
internal static void CreateClaimFromObject(List<Claim> claims, string claimType, object value, string issuer)
{
// Json.net recognized DateTime by default.
if (value is string str)
claims.Add(new Claim(claimType, str, JwtTokenUtilities.GetStringClaimValueType(str, claimType), issuer, issuer));
else if (value is int i)
claims.Add(new Claim(claimType, i.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer32, issuer, issuer));
else if (value is long l)
claims.Add(new Claim(claimType, l.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer64, issuer, issuer));
else if (value is bool b)
{
// Can't just use ToString or bools will get encoded as True/False instead of true/false.
if (b)
claims.Add(new Claim(claimType, "true", ClaimValueTypes.Boolean, issuer, issuer));
else
claims.Add(new Claim(claimType, "false", ClaimValueTypes.Boolean, issuer, issuer));
}
else if (value is double d)
claims.Add(new Claim(claimType, d.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Double, issuer, issuer));
else if (value is DateTime dt)
claims.Add(new Claim(claimType, dt.ToString("o", CultureInfo.InvariantCulture), ClaimValueTypes.DateTime, issuer, issuer));
else if (value is float f)
claims.Add(new Claim(claimType, f.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Double, issuer, issuer));
else if (value is decimal m)
claims.Add(new Claim(claimType, m.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Double, issuer, issuer));
else if (value is null)
claims.Add(new Claim(claimType, string.Empty, JsonClaimValueTypes.JsonNull, issuer, issuer));
else if (value is IList ilist)
{
foreach (var item in ilist)
CreateClaimFromObject(claims, claimType, item, issuer);
}
else if (value is JsonElement j)
if (j.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement jsonElement in j.EnumerateArray())
{
Claim claim = CreateClaimFromJsonElement(claimType, issuer, jsonElement);
if (claim != null)
claims.Add(claim);
}
}
else
{
Claim claim = CreateClaimFromJsonElement(claimType, issuer, j);
if (claim != null)
claims.Add(claim);
}
}
internal static Claim CreateClaimFromJsonElement(string claimType, string issuer, JsonElement jsonElement)
{
// Json.net recognized DateTime by default.
if (jsonElement.ValueKind == JsonValueKind.String)
{
string claimValue = jsonElement.ToString();
return new Claim(claimType, claimValue, JwtTokenUtilities.GetStringClaimValueType(claimValue, claimType), issuer, issuer);
}
else if (jsonElement.ValueKind == JsonValueKind.Null)
return new Claim(claimType, string.Empty, JsonClaimValueTypes.JsonNull, issuer, issuer);
else if (jsonElement.ValueKind == JsonValueKind.Object)
return new Claim(claimType, jsonElement.ToString(), JsonClaimValueTypes.Json, issuer, issuer);
else if (jsonElement.ValueKind == JsonValueKind.False)
return new Claim(claimType, "false", ClaimValueTypes.Boolean, issuer, issuer);
else if (jsonElement.ValueKind == JsonValueKind.True)
return new Claim(claimType, "true", ClaimValueTypes.Boolean, issuer, issuer);
else if (jsonElement.ValueKind == JsonValueKind.Number)
{
if (jsonElement.TryGetInt32(out int i))
return new Claim(claimType, i.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer32, issuer, issuer);
else if (jsonElement.TryGetInt64(out long l))
return new Claim(claimType, l.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer64, issuer, issuer);
else if (jsonElement.TryGetDouble(out double d))
return new Claim(claimType, d.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Double, issuer, issuer);
else if (jsonElement.TryGetUInt32(out uint u))
return new Claim(claimType, u.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.UInteger32, issuer, issuer);
else if (jsonElement.TryGetUInt64(out ulong ul))
return new Claim(claimType, ul.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.UInteger64, issuer, issuer);
else if (jsonElement.TryGetSingle(out float f))
return new Claim(claimType, f.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Double, issuer, issuer);
else if (jsonElement.TryGetDecimal(out decimal m))
return new Claim(claimType, m.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Double, issuer, issuer);
}
else if (jsonElement.ValueKind == JsonValueKind.Array)
{
return new Claim(claimType, jsonElement.ToString(), JsonClaimValueTypes.JsonArray, issuer, issuer);
}
return null;
}
internal Claim GetClaim(string key, string issuer)
{
if (key == null)
throw LogHelper.LogArgumentNullException(nameof(key));
if (_jsonClaims.TryGetValue(key, out object _))
{
foreach (var claim in Claims(issuer))
if (claim.Type == key)
return claim;
}
throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX14304, key)));
}
internal string GetStringValue(string key)
{
if (_jsonClaims.TryGetValue(key, out object obj))
{
if (obj == null)
return null;
return obj.ToString();
}
return string.Empty;
}
internal DateTime GetDateTime(string key)
{
long l = GetValue<long>(key, false, out bool found);
if (found)
return EpochTime.DateTime(l);
return DateTime.MinValue;
}
internal T GetValue<T>(string key)
{
return GetValue<T>(key, true, out bool _);
}
/// <summary>
/// Retrieves a value of the specified type associated with the given claim from a JWT token.
/// The 5 basic types: number, string, true/false, nil, array (of basic types).
/// This method is not designed to handle complex types.
/// For that we would need to provide a way to hook a JsonConverter to for complex types.
/// </summary>
/// <typeparam name="T">The type of the value to retrieve.</typeparam>
/// <param name="key">The key associated with the claim to retrieve.</param>
/// <param name="throwEx">Indicates whether to throw an exception if the key is not found.</param>
/// <param name="found">Outputs a boolean indicating whether the key was found.</param>
/// <returns>The value associated with the specified key.</returns>
internal T GetValue<T>(string key, bool throwEx, out bool found)
{
found = _jsonClaims.TryGetValue(key, out object obj);
if (!found)
return throwEx ? throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX14304, key))) : default;
if (obj == null)
if (typeof(T) == typeof(object) || typeof(T).IsClass || Nullable.GetUnderlyingType(typeof(T)) != null)
return (T)(object)null;
else
return default;
Type objType = obj.GetType();
if (typeof(T) == objType)
return (T)(obj);
if (typeof(T) == typeof(object))
return (T)obj;
// When the JsonClaimSet is created JsonArray and JsonObject are stored as JsonElement's
if (obj is JsonElement jsonElement)
{
if (JsonSerializerPrimitives.TryCreateTypeFromJsonElement<T>(jsonElement, out T t))
return t;
}
// the below here should only be simple types, string, int, ...
else if (typeof(T) == typeof(string))
{
if (objType == typeof(DateTime))
return (T)((object)((DateTime)obj).ToString("o", CultureInfo.InvariantCulture));
if (obj is List<string> list)
{
if (list.Count == 1)
return (T)((object)(list[0]));
}
else
return (T)((object)obj.ToString());
}
else if (typeof(T) == typeof(bool))
{
if (bool.TryParse(obj.ToString(), out bool value))
return (T)(object)value;
}
else if (typeof(T) == typeof(int))
{
if (int.TryParse(obj.ToString(), out int value))
return (T)(object)value;
}
else if (typeof(T) == typeof(long))
{
if (objType == typeof(int))
return (T)(object)(long)(int)obj;
if (long.TryParse(obj.ToString(), out long value))
return (T)(object)value;
}
else if (typeof(T) == typeof(string[]))
{
if (objType == typeof(string))
return (T)(object)new string[] { (string)obj };
if (objType == typeof(DateTime))
return (T)(object)new string[] { ((DateTime)obj).ToString("o", CultureInfo.InvariantCulture) };
return (T)(object)new string[] { obj.ToString() };
}
else if (typeof(T) == typeof(List<string>))
{
if (objType == typeof(string))
return (T)(object)new List<string> { (string)obj };
if (objType == typeof(DateTime))
return (T)(object)new List<string> { ((DateTime)obj).ToString("o", CultureInfo.InvariantCulture) };
return (T)(object)new List<string> { obj.ToString() };
}
else if (typeof(T) == typeof(Collection<string>))
{
if (objType == typeof(string))
return (T)(object)new Collection<string> { (string)obj };
if (objType == typeof(DateTime))
return (T)(object)new Collection<string> { ((DateTime)obj).ToString("o", CultureInfo.InvariantCulture) };
return (T)(object)new Collection<string> { obj.ToString() };
}
// we could have added an OR condition to List<string>
// but we have set an order of preference for the return types: Collection<string> is preferred over IList<string>
else if (typeof(T) == typeof(IList<string>))
{
if (objType == typeof(string))
return (T)(object)new List<string> { (string)obj };
if (objType == typeof(DateTime))
return (T)(object)new List<string> { ((DateTime)obj).ToString("o", CultureInfo.InvariantCulture) };
return (T)(object)new List<string> { obj.ToString() };
}
// we could have added an OR condition to Collection<string>
// but we have set an order of preference for the return types:
// string[], List<string>, Collection<string>, IList<string>, ICollection<string>
else if (typeof(T) == typeof(ICollection<string>))
{
if (objType == typeof(string))
return (T)(object)new Collection<string> { (string)obj };
if (objType == typeof(DateTime))
return (T)(object)new Collection<string> { ((DateTime)obj).ToString("o", CultureInfo.InvariantCulture) };
return (T)(object)new Collection<string> { obj.ToString() };
}
else if (typeof(T) == typeof(object[]))
return (T)(object)new object[] { obj };
else if (typeof(T) == typeof(List<object>))
return (T)(object)new List<object> { obj };
else if (typeof(T) == typeof(Collection<object>))
return (T)(object)new Collection<object> { obj };
else if (typeof(T).IsEnum)
{
return (T)Enum.Parse(typeof(T), obj.ToString(), ignoreCase: true);
}
else if (typeof(T) == typeof(DateTime))
{
if (DateTime.TryParse(obj.ToString(), out DateTime value))
return (T)(object)value;
}
else if (typeof(T) == typeof(int[]))
{
if (objType == typeof(int))
return (T)(object)new int[] { (int)obj };
if (int.TryParse(obj.ToString(), out int value))
return (T)(object)new int[] { value };
}
else if (typeof(T) == typeof(long[]))
{
if (objType == typeof(long))
return (T)(object)new long[] { (long)obj };
if (objType == typeof(int))
return (T)(object)new long[] { (int)obj };
if (long.TryParse(obj.ToString(), out long value))
return (T)(object)new long[] { value };
}
else if (typeof(T) == typeof(double))
{
if (double.TryParse(obj.ToString(), out double value))
return (T)(object)value;
}
else if (typeof(T) == typeof(uint))
{
if (uint.TryParse(obj.ToString(), out uint value))
return (T)(object)value;
}
else if (typeof(T) == typeof(ulong))
{
if (ulong.TryParse(obj.ToString(), out ulong value))
return (T)(object)value;
}
else if (typeof(T) == typeof(float))
{
if (float.TryParse(obj.ToString(), out float value))
return (T)(object)value;
}
else if (typeof(T) == typeof(decimal))
{
if (decimal.TryParse(obj.ToString(), out decimal value))
return (T)(object)value;
}
found = false;
if (throwEx)
throw LogHelper.LogExceptionMessage(
new ArgumentException(
LogHelper.FormatInvariant(
LogMessages.IDX14305,
LogHelper.MarkAsNonPII(key),
LogHelper.MarkAsNonPII(typeof(T)),
LogHelper.MarkAsNonPII(objType),
obj.ToString())));
else
LogHelper.LogExceptionMessage(
new ArgumentException(
LogHelper.FormatInvariant(
LogMessages.IDX14305,
LogHelper.MarkAsNonPII(key),
LogHelper.MarkAsNonPII(typeof(T)),
LogHelper.MarkAsNonPII(objType),
obj.ToString())));
return default;
}
internal bool TryGetClaim(string key, string issuer, out Claim claim)
{
claim = null;
if (!_jsonClaims.TryGetValue(key, out object value))
return false;
foreach (Claim c in Claims(issuer))
if (c.Type == key)
{
claim = c;
return true;
}
return false;
}
/// <summary>
/// The return types that are expected in a JWT token.
/// The 5 basic types: number, string, true/false, nil, array (of basic types).
/// This is not a general purpose translation layer for complex types.
/// For that, we would need to provide a way to hook a JsonConverter for complex types.
/// </summary>
/// <typeparam name="T">The type of the value to retrieve.</typeparam>
/// <param name="key">The key associated with the value to retrieve.</param>
/// <param name="value">The retrieved value associated with the specified key, if found.</param>
/// <returns><see langword="true"/> if the key was found; otherwise, <see langword="false"/>.</returns>
internal bool TryGetValue<T>(string key, out T value)
{
value = GetValue<T>(key, false, out bool found);
return found;
}
internal bool HasClaim(string claimName)
{
return _jsonClaims.TryGetValue(claimName, out _);
}
}
}