/
JsonKeyClaimAction.cs
63 lines (57 loc) · 2.07 KB
/
JsonKeyClaimAction.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Claims;
using System.Text.Json;
namespace Microsoft.AspNetCore.Authentication.OAuth.Claims;
/// <summary>
/// A ClaimAction that selects a top level value from the json user data with the given key name and adds it as a Claim.
/// This no-ops if the key is not found or the value is empty.
/// </summary>
public class JsonKeyClaimAction : ClaimAction
{
/// <summary>
/// Creates a new JsonKeyClaimAction.
/// </summary>
/// <param name="claimType">The value to use for Claim.Type when creating a Claim.</param>
/// <param name="valueType">The value to use for Claim.ValueType when creating a Claim.</param>
/// <param name="jsonKey">The top level key to look for in the json user data.</param>
public JsonKeyClaimAction(string claimType, string valueType, string jsonKey)
: base(claimType, valueType)
{
JsonKey = jsonKey;
}
/// <summary>
/// The top level key to look for in the json user data.
/// </summary>
public string JsonKey { get; }
/// <inheritdoc />
public override void Run(JsonElement userData, ClaimsIdentity identity, string issuer)
{
if (!userData.TryGetProperty(JsonKey, out var value))
{
return;
}
if (value.ValueKind == JsonValueKind.Array)
{
foreach (var v in value.EnumerateArray())
{
AddClaim(v.ToString()!, identity, issuer);
}
}
else if (value.ValueKind == JsonValueKind.Object || value.ValueKind == JsonValueKind.Undefined)
{
// Skip, because they were previously skipped
}
else
{
AddClaim(value.ToString()!, identity, issuer);
}
}
private void AddClaim(string value, ClaimsIdentity identity, string issuer)
{
if (!string.IsNullOrEmpty(value))
{
identity.AddClaim(new Claim(ClaimType, value, ValueType, issuer));
}
}
}