Reputation: 2539
I know that I can add a policy for my JWT custom claim this way:
services.AddAuthorization(options =>
{
options.AddPolicy("HasRole", policy => policy.RequireClaim("role", "Teacher"));
});
However, my JWT token has an array of roles:
// parsed jwt token
{
...,
roles: ['Teacher', 'Parent', 'Admin']
...
}
And I don't know how to rewrite the above code:
services.AddAuthorization(options =>
{
options.AddPolicy("IsTeacher",
policy => policy.RequireClaim("roles", /*what should I write here*/));
});
How can I require an item of an array in RequireClaim
?
Upvotes: 1
Views: 5997
Reputation: 1276
You can set your policies according to your roles with RequireRole():
services.AddAuthorization(o =>
{
// Teacher or admin can access.
o.AddPolicy("RequireTeacherRole", p => p.RequireRole("teacher", "admin"));
// Only admin can access.
o.AddPolicy("RequireAdminRole", p => p.RequireRole("admin"));
});
Now you can protect your MVC/API controllers or razor pages
[Authorize(Policy = "RequireTeacherRole")]
public class MyController : Controller
{
// ...
}
Upvotes: 2