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

Missing Roles Claims in the ASP.NET Core 2 and IdentityServer4

我阅读了 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.

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

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

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);
    }
  ...
}