I just finished my logging/logout code on my asp.net web core application and I am having a problem where the server always returns error 403 forbidden when trying to access a method that needs a specific role. What can be the problem? I checked the database and the role assignment is working fine.
here is an example of a method I wrote for the test:
[Authorize(Roles = "SuperAdmin")]
[HttpGet]
[Route("Test")]
public string Test()
{
return "role checking working";
}
My actual user does have the role “SuperAdmin” but I still get the forbidden from the server, by the way, I made sure to send the token with the request. When I tried just [Authorize], the check works fine since I only access that method when logged in.
Could it be the code generating the token? since I had no idea how to do that part and I just followed a tutorial brainlessly
Edit:
here is my claims variable when creating the token
var claims = new[]{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
what should I add to it?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Found the solution, I thought that the token I was creating contains the user information and his roles but I actually needed to add them manually, here is the right claims code that adds the roles to the token.
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var userRoles = await userManager.GetRolesAsync(user);
foreach (var userRole in userRoles)
{
claims.Add(new Claim(ClaimTypes.Role, userRole));
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0