【问题标题】:Authorization Role/Policy Attributes Not Working In .Net Core 3授权角色/策略属性在 .Net Core 3 中不起作用
【发布时间】:2020-02-10 20:28:29
【问题描述】:

我没有运气让任何角色或策略属性在 .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):

配置服务的其他部分:

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】:

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

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

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

    演示

    【讨论】:

    • 你是对的,谢谢你的帮助!你知道为什么policy.RequireRole("admin") 不起作用但policy.RequireClaim(ClaimTypes.Role, "admin") 起作用吗?
    • @levitatejay 据我所知,http://schemas.microsoft.com/ws/2008/06/identity/claims/role 是 dotnet core 中的标准方式。但是,虽然转换为我们映射了角色,但它并没有同时改变内部的_roleClaimType 字段,这使得User.IsInRole() 不可用,因此您的policy.RequireRole("admin") 不起作用。
    • @itminus 谢谢!有没有办法修复它,所以 RequireRole("admin") 可以工作?
    猜你喜欢
    • 2020-02-16
    • 1970-01-01
    • 2020-02-21
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2011-09-03
    • 1970-01-01
    相关资源
    最近更新 更多