Auth0 Home Blog Docs

Manually Added Roles to Access Token is Not Authorizing API Methods

Hello everyone,

I have added roles to the auth0 access token using the JwtSecurityTokenHandler and JwtSecurityToken.

var handler = new JwtSecurityTokenHandler();
var token = handler.ReadToken(jwtToken) as JwtSecurityToken;
token.Payload["http://schemas.microsoft.com/ws/2008/06/identity/claims/role"] = new string[] { "HR","Participant","Teacher"};            
var newjwt = handler.WriteToken(token);

The Roles are added successfully in the access token and I’m able access the roles from the new jwt token by Reading the Token.

var newToken = handler.ReadToken(newjwt) as JwtSecurityToken;
var roleClaims = newToken.Claims.Where(x => x.Type == System.Security.Claims.ClaimsIdentity.DefaultRoleClaimType).Select(x => x.Value).ToList();

But when I send this new token to authorize my API controller method its not authorizing. Its returning 401 Unauthorized.

Kindly help me to make it work and let me know if I need to do any other changes.
Any guidance would be appreciated.

Based on your post it looks like you are getting an Auth0 access_token in your application, then adding roles to it before using it to access an API, is this a correct assumption?

If this is the case, you are tampering with the token which may be why you are getting a 401 unauthorized.

Is there a reason you aren’t adding the roles in an Auth0 rule, rather than in your app? Doing it this way is the preferred and safer way.

In the Auth0 dashboard go to Users & Roles > Users and in each user’s app_metadata you can set their Role

Then in a rule you can access the users metadata, retrieve their role and add it to the access_token

Don’t forget to validate the token in your API.

If your issue persists, hopefully the link below can help you troubleshoot further
ASP.NET Web API (OWIN): Troubleshooting

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.