【问题标题】:How to map MapUniqueJsonKey for Json Claim Type如何为 Json 声明类型映射 MapUniqueJsonKey
【发布时间】:2020-07-30 18:54:02
【问题描述】:

我正在使用 Identity Server 4 和 UserProfileService 为用户提供自定义声明。

有两种情况需要介绍:

  1. Mvc 应用程序需要通过中间件访问 UserClaims
  2. 其他非 .Net 应用程序需要访问 UserClaims(例如 Postman 或 React)

我尝试了两种方法,但仍然无法满足以上两个要求:

方法一:使用IdentityServerConstants.ClaimValueTypes.Json

在 UserProfileService.cs 中,我添加了如下声明:

var roles= new List<string>
{
    "products.read", "products.write", "products.delete"
};

claims.Add(new Claim("roles", JsonConvert.SerializeObject(roles), IdentityServerConstants.ClaimValueTypes.Json));

我生成了 AccessToken 并将请求发送到 UserInfoEndpoint。我成功得到了以下结果:

{
    "user_id": "950d44f1-d19e-412b-9fad-e0b59c11b2ec",
    ...
    "roles": [
        "products.read",
        "products.write",
        "products.delete"
    ],
    "sub": "950d44f1-d19e-412b-9fad-e0b59c11b2ec"
}

然后,我在 Mvc application\Startup.cs 中添加了这个

options.ClaimActions.MapUniqueJsonKey("roles", "roles", "json");

但是,在我的 Mvc 应用程序中,我收到了错误,它无法反序列化声明中的角色数组。

InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken.
Newtonsoft.Json.Linq.Extensions.Convert<T, U>(T token)

方法二:不使用IdentityServerConstants.ClaimValueTypes.Json

如果我在添加声明类型时删除了 IdentityServerConstants.ClaimValueTypes.Json),它可以在 MVC 应用程序中使用。但它在邮递员中显示为字符串而不是 Json 对象。见下文:

{
    "user_id": "950d44f1-d19e-412b-9fad-e0b59c11b2ec",    
    "permissions": "[\"products.read\",\"products.write\",\"products.delete\"]",
    "sub": "950d44f1-d19e-412b-9fad-e0b59c11b2ec"
}

我只是想知道,这是设计使然还是我做错了什么?

有没有办法将声明保留为 Json 格式并使 Mvc 声明映射适用于声明中的字符串数组?

【问题讨论】:

    标签: .net-core identityserver4 claims


    【解决方案1】:

    我意识到这是一篇旧帖子,但我偶然发现了它,因为我遇到了类似的问题。我的access_token 没问题,但.AspNetCore.Cookie 分块cookie 集中缺少角色。这导致我在调用 API 时具有正确的角色,因此无法在 Web 客户端中使用 Use.IsInRole()

    我通过使用 MapJsonKey() 而不是 MapUniqueJsonKey() 来修复它

    就我而言:

    options.ClaimActions.MapJsonKey(JwtClaimTypes.Role, JwtClaimTypes.Role);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-28
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多