如何制作和使用基于 JWT 角色的身份验证?

How do I make and use JWT role based authentication?

我按照下面的教程 link 进行操作。

https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

我想了解它是如何工作的,我想使用此令牌使用基于角色的身份验证。所以我在 Startup.cs 文件中制定了另一个政策,如下所示。

我尝试在控制器中像 [Authorize(Policy = "admin")][Authorize(Policy = "ApiUser")] 那样使用它,但每次我尝试使用 postman 时我都会得到 unauthenticated。 我错过了什么?如何根据教程进行基于角色的身份验证?

启动

services.AddAuthorization(options =>
{
    options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
});
services.AddAuthorization(options =>
    options.AddPolicy("admin", policy => policy.RequireRole("admin"))
);


授权控制器

// POST api/auth/login
[HttpPost("login")]
public async Task<IActionResult> Post([FromBody]CredentialsViewModel credentials)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);



    if (identity == null)
    {
        //return null;
        return BadRequest(Error.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
    }
    var id = identity.Claims.Single(c => c.Type == "id").Value; 
    var user = await _userManager.FindByIdAsync(id);
    IList<string> role = await _userManager.GetRolesAsync(user);
    var jwt = await Tokens.GenerateJwt(identity, role[0], _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });


    return new OkObjectResult(jwt);

}

我尝试了所有的方法,none 有效

[Authorize(Policy = "ApiUser")]
[HttpGet("getPolicy")]
public string GetPolicy()
{
    return "policyWorking";
}
[Authorize(Roles = "admin")]
[HttpGet("getAdmin")]
public string GetAdmin()
{
    return "adminWorking";
}
[Authorize ]
[HttpGet("getAuthorize")]
public string GetAuthorize()
{
    return "normal authorize Working";
}

我使用 this 教程制作了我的。

它也适用于 .Net Core 3.1。

@更新

我为此使用政策:

services.AddAuthorization(options => {
    options.AddPolicy(Policies.RequireAny, policy =>
        policy.RequireClaim(JwtClaimTypes.Role, Enum.GetNames(typeof(AvailableRoles))));
    options.AddPolicy(Policies.RequireAdmin, policy =>
        policy.RequireClaim(JwtClaimTypes.Role,
            AvailableRoles.Admin.ToString()));
});

并在控制器中

[HttpDelete("{id:int:min(1)}")]
[Authorize(Policy = Policies.RequireAdmin)]
public async Task<IActionResult> Delete(int id) {
    // CODE
    return Ok();
}

并在创建 JWT 令牌时:


// Other claims and code...

claims.Add(new Claim(JwtClaimTypes.Role, roles[0]))
var token = new JwtSecurityToken(
    issuer:_appSettings.AppUrl,
    audience:_appSettings.AppUrl,
    claims: claims,
    expires: expires,
    signingCredentials: credentials
);

return new JwtSecurityTokenHandler().WriteToken(token);

首先,请确保您在 appsettings.json 中添加了 json 字符串,否则您将始终得到 401 unauthorized:

"JwtIssuerOptions": {
    "Issuer": "webApi",
    "Audience": "http://localhost:5000/"
}

What am I missing? how to make roles-based authentication based on the tutorial?

1.If您要使用以下方式注册服务:

services.AddAuthorization(options =>
    options.AddPolicy("admin", policy => policy.RequireRole("admin"))
);

授权属性应如下所示:

[Authorize(Policy  = "admin")]

2.If您要使用以下方式:

[Authorize(Roles = "admin")]

您需要从 Startup.cs 中删除服务:

//services.AddAuthorization(options =>
//    options.AddPolicy("admin", policy => policy.RequireRole("admin"))
//);

然后,不要忘记在 JwtFactory.GenerateEncodedToken 中添加角色声明,如下所示:

public async Task<string> GenerateEncodedToken(string userName, ClaimsIdentity identity)
{
    var claims = new[]
    {
            new Claim(JwtRegisteredClaimNames.Sub, userName),
            new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
            new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
            identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol),
            identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id),
            new Claim(ClaimTypes.Role,"admin")
    };
        //...
}