From e09dd6d0b8fad0a6d0f7c52931549006e794693e Mon Sep 17 00:00:00 2001 From: Troy Dai Date: Thu, 29 Sep 2016 16:21:26 -0700 Subject: [PATCH] Fix #976: Break claims value in array into multiple claims (#996) * Break claims value in array into multiple claims * Review feedback 1 --- .../OpenIdConnectHandler.cs | 7 +--- .../Utility/ClaimsHelper.cs | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 src/Microsoft.AspNetCore.Authentication.OpenIdConnect/Utility/ClaimsHelper.cs diff --git a/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/OpenIdConnectHandler.cs b/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/OpenIdConnectHandler.cs index 2039a76e90..1e5eda4707 100644 --- a/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/OpenIdConnectHandler.cs +++ b/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/OpenIdConnectHandler.cs @@ -806,12 +806,7 @@ namespace Microsoft.AspNetCore.Authentication.OpenIdConnect } // adding remaining unique claims from userinfo endpoint to the identity - foreach (var pair in user) - { - JToken value; - var claimValue = user.TryGetValue(pair.Key, out value) ? value.ToString() : null; - identity.AddClaim(new Claim(pair.Key, claimValue, ClaimValueTypes.String, jwt.Issuer)); - } + ClaimsHelper.AddClaimsToIdentity(user, identity, jwt.Issuer); return AuthenticateResult.Success(ticket); } diff --git a/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/Utility/ClaimsHelper.cs b/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/Utility/ClaimsHelper.cs new file mode 100644 index 0000000000..dab4d0fd9c --- /dev/null +++ b/src/Microsoft.AspNetCore.Authentication.OpenIdConnect/Utility/ClaimsHelper.cs @@ -0,0 +1,36 @@ +// 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.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, ClaimValueTypes.String, issuer)); + } +}