Update ClaimsHelper.AddClaimsToIdentity to infer the claim value type from the JSON token type (#1002)

This commit is contained in:
Kévin Chalet 2016-10-24 18:28:25 +02:00 committed by Troy Dai
parent b3fdac568f
commit 8fcbddc23b
1 changed files with 46 additions and 1 deletions

View File

@ -1,6 +1,7 @@
// 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;
@ -31,6 +32,50 @@ namespace Microsoft.AspNetCore.Authentication.OpenIdConnect
}
private static void AddClaimsToIdentity(JToken item, ClaimsIdentity identity, string key, string issuer)
=> identity.AddClaim(new Claim(key, item?.ToString() ?? string.Empty, ClaimValueTypes.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;
}
}
}