Sorry I lost my password for this account but I already have a solution on how to implement role base authorization using JWT token bearer.
var user = _userRepository.CheckLogin(login);
if (user.UserID > 0)
{
var _userManager = HttpContext.User.Claims;
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Token:SecretKey"]));
var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha512);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.UniqueName, user.Username), // ClaimType.Name
new Claim(JwtRegisteredClaimNames.Email, user.EmailAddress), // ClaimType.EmailAddress
new Claim(JwtRegisteredClaimNames.NameId, user.UserID.ToString()), // ClaimType.NameIdentifier
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), // jti
new Claim(JwtRegisteredClaimNames.Actort, user.UserKey), // ClaimType.Actor
new Claim(ClaimTypes.Role, user.Type) // ClaimType.Role add role for authorization.
};
var stringToken = new JwtSecurityToken(
_configuration["Token:Issuer"],
_configuration["Token:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(Convert.ToInt32(_configuration["Token:ExpirationMinutes"])),
notBefore: DateTime.Now,
signingCredentials: credentials
);
var userToken = new JwtSecurityTokenHandler().WriteToken(stringToken);
return Ok(new { token = userToken });
}
Adding the ClaimTypes.Role
in your claims list will fix this and now you can use [Authorize(Roles = "???")]
to your controller now.
I hope this will help anyone out there that are using JWT Bearer authentication adding roles.