ASP.NET Core JWT mapping role claims to ClaimsIdentity

asked8 years ago
last updated7 years ago
viewed104.1k times
Up Vote42Down Vote

I want to protect ASP.NET Core Web API using JWT. Additionally, I would like to have an option of using roles from tokens payload directly in controller actions attributes.

Now, while I did find it out how to use it with Policies:

Authorize(Policy="CheckIfUserIsOfRoleX")
ControllerAction()...

I would like better to have an option to use something usual like:

Authorize(Role="RoleX")

where Role would be automatically mapped from JWT payload.

{
    name: "somename",
    roles: ["RoleX", "RoleY", "RoleZ"]
}

So, what is the easiest way to accomplish this in ASP.NET Core? Is there a way to get this working automatically through some settings/mappings (if so, where to set it?) or should I, after token is validated, intercept generation of ClaimsIdentity and add roles claims manually (if so, where/how to do that?)?