【发布时间】:2020-07-30 18:54:02
【问题描述】:
我正在使用 Identity Server 4 和 UserProfileService 为用户提供自定义声明。
有两种情况需要介绍:
- Mvc 应用程序需要通过中间件访问 UserClaims
- 其他非 .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