/
ClaimsExtensions.cs
98 lines (83 loc) · 2.4 KB
/
ClaimsExtensions.cs
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
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.
using IdentityModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Json;
namespace Duende.IdentityServer.Extensions;
internal static class ClaimsExtensions
{
public static Dictionary<string, object> ToClaimsDictionary(this IEnumerable<Claim> claims)
{
var d = new Dictionary<string, object>();
if (claims == null)
{
return d;
}
var distinctClaims = claims.Distinct(new ClaimComparer());
foreach (var claim in distinctClaims)
{
if (!d.ContainsKey(claim.Type))
{
d.Add(claim.Type, GetValue(claim));
}
else
{
var value = d[claim.Type];
if (value is List<object> list)
{
list.Add(GetValue(claim));
}
else
{
d.Remove(claim.Type);
d.Add(claim.Type, new List<object> { value, GetValue(claim) });
}
}
}
return d;
}
private static object GetValue(Claim claim)
{
if (claim.ValueType == ClaimValueTypes.Integer ||
claim.ValueType == ClaimValueTypes.Integer32)
{
if (Int32.TryParse(claim.Value, out var value))
{
return value;
}
}
if (claim.ValueType == ClaimValueTypes.Integer64)
{
if (Int64.TryParse(claim.Value, out var value))
{
return value;
}
}
if (claim.ValueType == ClaimValueTypes.Double)
{
if (Double.TryParse(claim.Value, out var value))
{
return value;
}
}
if (claim.ValueType == ClaimValueTypes.Boolean)
{
if (bool.TryParse(claim.Value, out var value))
{
return value;
}
}
if (claim.ValueType == IdentityServerConstants.ClaimValueTypes.Json)
{
try
{
return System.Text.Json.JsonSerializer.Deserialize<JsonElement>(claim.Value);
}
catch { }
}
return claim.Value;
}
}