我在从 API 中的 JWT token 捕获用户角色时遇到问题。我向我的 token 添加了一个角色,并添加了具有所需角色的策略,但它没有按我的预期工作。每次当我响应状态为 403 Forbidden 时。 IdentityServer站点:
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResource(
name: "user",
userClaims: new[] {JwtClaimTypes.Email}),
new IdentityResource(
name: "role",
userClaims: new[] {JwtClaimTypes.Role})
};
new Client()
{
ClientId = "swagger",
ClientName = "Client for Swagger use",
AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
ClientSecrets = {new Secret("secret".Sha256())},
AllowedScopes = {"api1", "user", "openid", "role"},
AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true,
AllowAccessTokensViaBrowser = true,
RedirectUris = {"https://localhost:44376/swagger/oauth2-redirect.html"},
AllowedCorsOrigins = {"https://localhost:44376"}
}
API 站点:
services.AddAuthorization(optionns =>
{
optionns.AddPolicy("admin", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "api1");
policy.RequireRole("admin");
});
optionns.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "api1");
});
});
Controller 站点:
[Authorize(Policy = "admin")]
或
[Authorize(Role= "admin")]
我的 JWT token 数据:
{
"nbf": 1670283035,
"exp": 1670286635,
"iss": "https://localhost:5001",
"aud": "https://localhost:5001/resources",
"client_id": "swagger",
"sub": "1",
"auth_time": 1670282526,
"idp": "local",
"Email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="783914111b1d2b15110c10381d15191114561b1715" rel="noreferrer noopener nofollow">[email protected]</a>",
"role": "admin",
"jti": "D07527BB11C8C4EEFC7A5012ADB38DE9",
"sid": "97828B78D66B3A2C96CAE60F7F1A6D25",
"iat": 1670283035,
"scope": [
"api1",
"user",
"openid",
"role"
],
"amr": [
"pwd"
]
}
有什么想法可以解决这个问题吗?我已经在论坛和教程上处理了数百个问题,但没有任何帮助。
最佳答案
Microsoft 和 OpenID-Connect 对于声明的名称有不同的看法。
因此,您在 AddOpenIDConnect 中需要做的是告诉 ASP.NET Core 角色声明的名称是什么,通常通过添加如下内容:
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = JwtClaimTypes.Name,
RoleClaimType = JwtClaimTypes.Role
};
解决这些问题的最佳方法是查看 ClaimsPrincipal User 对象中的实际内容。它可能并不总是包含您认为应包含的声明。
有关更多详细信息,请参阅此博文 https://leastprivilege.com/2017/11/15/missing-claims-in-the-asp-net-core-2-openid-connect-handler/
为了补充这个答案,我写了一篇博客文章,其中更详细地介绍了 关于此主题:Debugging OpenID Connect claim problems in ASP.NET Core
关于c# - Identity Server 4 - 角色策略不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74695749/