Authorize attribute not working with Role Based and JWT

I am using JWT and the "Authorize" attribute is working when its just the word "Authorize" but as soon as I add a type of role like

       [Authorize(Roles = "Admin")] 

it doesnt work

My JWT is created in one server and I pass it over to another server for validation

Here is my validation method

            token = this.tokenFromRequest;   <---- this jwttoken comes from the request header.              ClaimsPrincipal principal = null;                             string sec = "000uVmTXj5EzRjlnqruWF78JQZMT";             var now = DateTime.UtcNow;             var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));              SecurityToken securityToken;             JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();             string tokenIssuer = "MyToken"              //These are our validation parameters that come from the web config.              TokenValidationParameters validationParameters = new TokenValidationParameters()             {                 ValidAudience = tokenIssuer,                 ValidIssuer = tokenIssuer,                 ValidateLifetime = true,                 ValidateIssuerSigningKey = true,                 RoleClaimType = "role",                 LifetimeValidator = lifetimeValidator ?? DefaultLifetimeValidator,                 IssuerSigningKey = securityKey             };                 principal = handler.ValidateToken(token, validationParameters, out securityToken);                           Thread.CurrentPrincipal = principal;                 HttpContext.Current.User = principal; 

My decoded JWT Token looks like this so you can clearly see that Role is assigned as admin

{   "alg": "HS256",   "typ": "JWT" }.{   "unique_name": "Unique Name",   **"role": "Admin",**   "primarysid": "FirstName, LastName",   "email": "myemail.com",   "nameid": "FirstName, LastName",   "http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata": "Unique Name",   "Timestamp": "8/11/2020 1:55:27 PM",   "nbf": 1597168527,   "exp": 1597254927,   "iat": 1597168527,   "iss": "MyToken",   "aud": "MyToken" }.[Signature] 

Am I supposed to add the role somewhere so that the Authorize attribute will see the roles?

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.