ASP.NET Core 8 - User.IsInRole not working

35 Views Asked by At

I got all the role claims after successful login. But there must be a mapping mismatch between the name of the role claims and what ASP.NET expect.

User.IsInRole is not working, but I can get the roles with this code;

var roles = ((ClaimsPrincipal)identity).Claims.Where(m => m.Type == ClaimTypes.Role).Select(m => m.Value).ToList();

In services.AddAuthentication I have tried with the name "role" and "roles" for the mapping. Should be role as this is what I have in my JWT.

 options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "preferred_username",
                    RoleClaimType = "role",
                    ValidateIssuer = true
                };

This is part of my JWT

 "scope": "openid email profile",
    "sid": "8fac96c0-8c41-45f6-8074-7e5e18a35124",
    "email_verified": true,
    "role": [
      "ExternalPortfolioManager",
      "InternalFontViewer",
      "InternalDataManager",
      "ExternalTrader"
    ],

Feel that I am pretty close.

enter image description here

0

There are 0 best solutions below