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

问题描述 投票:0回答:1

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

这是我的政策:

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

这里是我的控制器:

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

我进行了自定义配置文件服务,将声明添加到令牌,

var claims = new List<Claim>();

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

context.IssuedClaims.AddRange(claims);

在我的访问令牌内部(来自jwt.io):

enter image description here

配置服务的其他部分:

services.AddDefaultIdentity<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

...

services.AddAuthentication()
    .AddIdentityServerJwt();

普通的[Authorize]标记与其他控制器上的访问令牌正常工作。

[当我用访问令牌击中该控制器时,我收到403响应

我缺少什么使它无法正常工作?

asp.net-core .net-core identityserver4 asp.net-core-identity .net-core-3.0
1个回答
0
投票

我尝试您的代码,发现role声明密钥已转换为standard Role ClaimsTypehttp://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

© www.soinside.com 2019 - 2024. All rights reserved.