Using Identity with token and cookie authenticatio

2019-08-13 17:40发布

问题:

Im trying to setup Token authentication with cookie authentication on same time in my application.

I created a MVC project in asp.net core 2.0, with individual user accounts to auth. Setup roles to the users too.

If i follow this tutorial of Shawn Wildermuth Two-AuthorizationSchemes-in-ASP-NET-Core-2

Everything works fine to get the Token of the registered user. But if i use the Role attribute on authorize [Authorize(Roles="Admin")] im getting a 403 response.

I think that is because the Token is not receiving the Role on auth.

How to setup this? Is any way to pass the Roles on the Token process?

To generate the token he is using this piece of code:

[AllowAnonymous] 
[HttpPost] 
public async Task<IActionResult> GenerateToken([FromBody] LoginViewModel model) {   if (ModelState.IsValid)   {
        var user = await _userManager.FindByEmailAsync(model.Email);

        if (user != null)
        {
          var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
          if (result.Succeeded)
          {

            var claims = new[]
            {
              new Claim(JwtRegisteredClaimNames.Sub, user.Email),
              new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

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

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

            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
          }
        }   }

      return BadRequest("Could not create token"); }

You guys have any idea?

Thanks

回答1:

If you add the following using and code, that should help.

using System.Security.Claims;

...

    var userRoles = await _userManager.GetRolesAsync(user);

    var claims = new[]
        {
          new Claim(JwtRegisteredClaimNames.Sub, user.Email),
          new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        }.Union(userRoles.Select(m => new Claim(ClaimTypes.Role, m)));

You can see the Union that adds the roles in with the type of ClaimTypes.Role, this will enable them to be used in the AuthorizeAttribute

HTH