I'm using asp.net core authorization.I have some roles like SuperAdmin ,Admin,User. Each user will be assigned one of them. SuperAdmin can change the role of any user.So basically i want dynamic role system. So where to map user-Role data and
[Authorize(Roles = "Admin")]
goes where to check the role of user? means where this thing checks the role.
I'm using Windows Authentication
You can use claims-based authorization via policies . After setting windows authentication in your application , you could add custom claim to ClaimsPrincipal ,check user's identity and confirm which permission/role the current user has :
You can add a claims transformation service to your application:
class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var id = ((ClaimsIdentity)principal.Identity);
var ci = new ClaimsIdentity(id.Claims, id.AuthenticationType, id.NameClaimType, id.RoleClaimType);
//read database or flies or query AD to confirm user role by use ci.Name(username)
if (....)
{
ci.AddClaim(new Claim("role", "Admin"));
}
else
{
ci.AddClaim(new Claim("role", "user"));
}
var cp = new ClaimsPrincipal(ci);
return Task.FromResult(cp);
}
}
Add to Startup.cs :
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
Set your policy :
services.AddAuthorization(options =>
{
options.AddPolicy("Admin", policy =>
policy.RequireClaim("role", "Admin"));
options.AddPolicy("User", policy =>
policy.RequireClaim("role", "user"));
});
Restrict access to a controller or action by requiring this policy:
[Authorize(Policy = "Admin")]
public IActionResult Contact()
{
.....
}
You can also use AD groups as roles . Base on your requirement , you can modify above codes to fit your scenario . Manage user/roles could use local database or ASP.NET Core Identity auto-create tables.