User.IsInRole 总是通过令牌认证返回 false

use*_*943 2 c# asp.net asp.net-core-2.0

我将 ASP.NET Core 2 配置为使用 JWT 令牌进行身份验证。配置如下所示:

services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;

    })
    .AddJwtBearer(options =>
    {
        options.RequireHttpsMetadata = false;
        options.SaveToken = true;

        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = Configuration["Tokens:Issuer"],
            ValidAudience = Configuration["Tokens:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
        };
    });
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个用户登录的方法,如下所示:

[AllowAnonymous]
[HttpPost]
[Route("token")]
public async Task<IActionResult> Token([FromBody] LoginViewModel model)
{
    if (!ModelState.IsValid) return BadRequest("Could not create token");

    var user = await _userManager.FindByNameAsync(model.UserName);

    if (user == null) return BadRequest("Could not create token");
    var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
    if (!result.Succeeded) return BadRequest("Could not create token");
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.Email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var roles = await _userManager.GetRolesAsync(user);

    var token = new JwtSecurityToken(_configuration["Tokens:Issuer"],
        _configuration["Tokens:Issuer"],
        claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: creds);

    return Ok(new {
        access_token = new JwtSecurityTokenHandler().WriteToken(token),
        roles });
}
Run Code Online (Sandbox Code Playgroud)

}

我保存令牌并在我的请求中使用它。我有一个非常简单的 api 端点:

[HttpGet("users")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IActionResult GetUsers()
{
    var isInRole = HttpContext.User.IsInRole(Roles.Administrator);
    return Ok(_service.GetAllUsers());
}
Run Code Online (Sandbox Code Playgroud)

在这里我得到了方法,但isInRole总是错误的。即使我var roles = await _userManager.GetRolesAsync(user);返回了包括管理员在内的角色列表。为什么这不起作用呢?

Den*_*doo 6

您需要claims像这样将 Role 声明添加到您的数组中

var claims = new[]
{
    new Claim(JwtRegisteredClaimNames.Sub, user.Email),
    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    //role claim
    new Claim(ClaimTypes.Role, "Administrator")
};
Run Code Online (Sandbox Code Playgroud)

这就是 Asp.Net 将在[Authorize(Roles="Administrator")]属性中查看的内容和HttpContext.User.IsInRole("Administrator");

同样ClaimTypes.Name用于User.Identity.Name在您的控制器中生产

我建议您阅读 Rui Figueiredo 撰写的关于在 ASP.NET Core 中保护 Web Api的优秀文章