Saturday, April 18, 2020

Easily adding Roles to ASP.NET Core

In the Startup.cs file add the basic authorization middleware. For options, add a new policy. This policy will check for the presence of the admin role claim.

services.AddAuthorization(options => {
   options.AddPolicy("admin", policy => policy.RequireClaim(ClaimTypes.Role,"admin"));
});

In the authentication controller, add the claims to the user.

claims.AddRange(user.Roles.Select(r => new Claim(ClaimTypes.Role, r)));

In the controller you want to secure, add the header to check the policy.

[Authorize("admin")]
public class AdminController : Controller {}

No comments:

Post a Comment