gpt4 book ai didi

asp.net-core - 授权角色/策略属性在 .Net Core 3 中不起作用

转载 作者:行者123 更新时间:2023-12-03 18:45:37 25 4
gpt4 key购买 nike

我没有运气在 .Net Core 3 中获得任何角色或策略属性。我从带有身份验证的 .Net Core Angular 入门项目开始我的项目。
我认为这与新的 .AddDefault 方法有关,所以我尽可能地简化了它,但它仍然不起作用。

这是我的政策:

services.AddAuthorization(options =>
{
options.AddPolicy("IsAdmin", policy =>
policy.RequireClaim("role", "admin"));
});

这是我的 Controller :
[Authorize(Policy = "IsAdmin")]
[Route("api/[controller]")]
public class AdminController : Controller
{
...

我创建了一个自定义配置文件服务,将声明添加到 token 中,
var claims = new List<Claim>();

if (await _userManager.IsInRoleAsync(user, "Admin"))
{
claims.Add(new Claim(JwtClaimTypes.Role, "admin"));
}

context.IssuedClaims.AddRange(claims);

在我的访问 token 中(来自 jwt.io):

enter image description here

配置服务的其他部分:
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

...

services.AddAuthentication()
.AddIdentityServerJwt();

平原 [Authorize]标签与其他 Controller 上的访问 token 一起工作正常。

当我用访问 token 点击这个 Controller 时,我得到一个 403回复

我错过了什么阻止它工作?

最佳答案

我尝试了您的代码,发现 role声明 key 已转换为 standard Role ClaimsType : http://schemas.microsoft.com/ws/2008/06/identity/claims/role
enter image description here

所以使用 ClaimTypes.Role将解决问题:

services.AddAuthorization(options => {
options.AddPolicy("IsAdmin", 策略 =>
{
policy.RequireClaim(ClaimTypes.Role,"admin");
});
});

演示

enter image description here

关于asp.net-core - 授权角色/策略属性在 .Net Core 3 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58372961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com