ASP.NET Core 2和IdentityServer4中缺少角色声明

时间:2018-09-24 13:28:59

标签: asp.net-core-2.0 identityserver4 roles claims-based-identity

我读了https://leastprivilege.com/2017/11/15/missing-claims-in-the-asp-net-core-2-openid-connect-handler/的有关以下代码行映射自定义声明的信息:

options.ClaimActions.MapUniqueJsonKey("website", "website");

我需要映射角色,并且直到我只有一个角色,例如“ User ”。

options.ClaimActions.MapUniqueJsonKey("role", "role");

问题是,当我有多个角色时,例如“ User ”和“ Superadmin ” 该代码行引发异常:

InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken.

有人知道吗?我错了什么吗,或者可能是个错误?

1 个答案:

答案 0 :(得分:1)

这里有一个关于这个问题的讨论:

https://github.com/aspnet/Security/issues/1383

并且在同一期中,您可以通过以下角色来解决您的问题:

https://github.com/aspnet/Security/issues/1383#issuecomment-361505163

oidcOptions.Events = new OpenIdConnectEvents()
{
  OnUserInformationReceived = async context =>
  {
    // IDS4 returns multiple claim values as JSON arrays, which break the authentication handler
    if (context.User.TryGetValue(JwtClaimTypes.Role, out JToken role))
    {
      var claims = new List<Claim>();
      if (role.Type != JTokenType.Array) {
        claims.Add(new Claim(JwtClaimTypes.Role, (string)role));
      }
      else  {
        foreach (var r in role)
          claims.Add(new Claim(JwtClaimTypes.Role, (string)r));
      }
      var id = context.Principal.Identity as ClaimsIdentity;
      id.AddClaims(claims);
    }
  ...
}