Repository navigation
Expand file tree
/
Copy pathClaimsHelper.cs
More file actions
81 lines (68 loc) · 2.6 KB
/
Copy pathClaimsHelper.cs
File metadata and controls
81 lines (68 loc) · 2.6 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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNetCore.Authentication.OpenIdConnect
{
internal static class ClaimsHelper
{
public static void AddClaimsToIdentity(
JObject userInformationPayload,
ClaimsIdentity identity,
string issuer)
{
foreach (var pair in userInformationPayload)
{
var array = pair.Value as JArray;
if (array != null)
{
foreach (var item in array)
{
AddClaimsToIdentity(item, identity, pair.Key, issuer);
}
}
else
{
AddClaimsToIdentity(pair.Value, identity, pair.Key, issuer);
}
}
}
private static void AddClaimsToIdentity(JToken item, ClaimsIdentity identity, string key, string issuer)
=> identity.AddClaim(new Claim(key, item?.ToString() ?? string.Empty, GetClaimValueType(item), issuer));
private static string GetClaimValueType(JToken token)
{
if (token == null)
{
return JsonClaimValueTypes.JsonNull;
}
switch (token.Type)
{
case JTokenType.Array:
return JsonClaimValueTypes.JsonArray;
case JTokenType.Boolean:
return ClaimValueTypes.Boolean;
case JTokenType.Date:
return ClaimValueTypes.DateTime;
case JTokenType.Float:
return ClaimValueTypes.Double;
case JTokenType.Integer:
{
var value = (long) token;
if (value >= int.MinValue && value <= int.MaxValue)
{
return ClaimValueTypes.Integer;
}
return ClaimValueTypes.Integer64;
}
case JTokenType.Object:
return JsonClaimValueTypes.Json;
case JTokenType.String:
return ClaimValueTypes.String;
}
// Fall back to ClaimValueTypes.String when no appropriate
// claim value type can be inferred from the claim value.
return ClaimValueTypes.String;
}
}
}