授权策略属性始终使用.net核心标识和JwtBearerAuthentication返回403禁止

Kol*_*lby 4 asp.net claims-based-identity jwt asp.net-identity asp.net-core

按照本指南,我可以使用身份验证

Microsoft.AspNetCore.Identity.EntityFrameworkCore
Microsoft.AspNetCore.Authentication.JwtBearer
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试使用角色或声明保护我的api端点.我尝试了两个相同的结果(403)

使用[Authorize]正常工作.

我的代码目前看起来像这样:

控制器:

[Authorize(Policy = "RequireUserRole")]
// Also tried [Authorize(Roles="User")]
public string Get()
{   
  return "YO";
}
Run Code Online (Sandbox Code Playgroud)

启动:

services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationContext>();
services.Configure<JWTSettings>(Configuration.GetSection("JWTSettings"));
services.AddAuthorization(options =>
{
        options.AddPolicy("RequireUserRole", policy => policy.RequireRole("User"));
});
Run Code Online (Sandbox Code Playgroud)

...

app.UseIdentity();

var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value;
var issuer = Configuration.GetSection("JWTSettings:Issuer").Value;
var audience = Configuration.GetSection("JWTSettings:Audience").Value;
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        TokenValidationParameters = new TokenValidationParameters
        {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = audience,

                ValidateLifetime = true
        }
});

app.UseMvcWithDefaultRoute();
Run Code Online (Sandbox Code Playgroud)

当我创建用户时,我将其分配给角色"用户"

await _userManager.AddToRoleAsync(user, "User");
Run Code Online (Sandbox Code Playgroud)

正在成功创建角色关系,但是在命中端点时对角色的验证失败.

任何帮助赞赏!

Kol*_*lby 11

答案在这篇mdsn博客文章中:

基于角色的授权可以通过ASP.NET身份开箱即用.只要用于身份验证的承载令牌包含角色元素,ASP.NET Core的JWT承载身份验证中间件将使用该数据为用户填充角色.

因此,可以将基于角色的授权属性(如[Authorize(Roles ="Manager,Administrator")]限制对管理员和管理员的访问权限)添加到API中并立即工作.

所以我在我的访问令牌对象中添加了一个名为roles的元素:

private string GetAccessToken(string userRole)
{
    var payload = new Dictionary<string, object>
    {
        ...
        { "roles", userRole } 
    };
    return GetToken(payload);
}
Run Code Online (Sandbox Code Playgroud)