1
votes

I have a web api which uses JWT Bearer Authentication. Now I want to know how to implement role-based authorization using the JWT token on asp.net core. I tried this aritcle using the Role-based authorization but I didn't get much help.

Does anyone has a good article to study or sample code on how to implement Role-based authorization?

Thanks.

2
asking for tutorials is usually regarded as off-topic on SO. Better ask a direct question about what you didn't understand or what doesn't work.jps

2 Answers

2
votes

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.

-2
votes

I have implemented role-based authorization using the JWT token on asp.net core with custom tables. I have placed sample working source code on Github and explained this in detail on medium.

Hope it helps.