我正在使用Identity Server 4和UserProfileService为用户提供自定义声明。
有两种情况需要讨论:
middleware
)
我尝试了两种方法,但仍然无法同时满足上述两种要求:
方法1:使用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)
方法2:不使用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索赔映射工作用于索赔中的字符串阵列?
发布于 2021-02-18 13:53:27
我意识到这是一个旧的职位,但我绊倒了,因为我有一个类似的问题。我的access_token
还好,但是.AspNetCore.Cookie
块cookie集中缺少角色。这导致当我调用API时具有正确的角色,所以我不能在web客户端中使用Use.IsInRole()
。
我用MapJsonKey()
而不是MapUniqueJsonKey()
修复了它
就我而言:
options.ClaimActions.MapJsonKey(JwtClaimTypes.Role, JwtClaimTypes.Role);
https://stackoverflow.com/questions/61268791
复制相似问题