From 8fcbddc23be1caff41f59f17b90624171fa8e43e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Chalet?= Date: Mon, 24 Oct 2016 18:28:25 +0200 Subject: [PATCH] Update ClaimsHelper.AddClaimsToIdentity to infer the claim value type from the JSON token type (#1002) --- .../Utility/ClaimsHelper.cs | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/Utility/ClaimsHelper.cs b/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/Utility/ClaimsHelper.cs index dab4d0fd9c..78eea68bfb 100644 --- a/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/Utility/ClaimsHelper.cs +++ b/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/Utility/ClaimsHelper.cs @@ -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; + } } }