I have a sample question with this post Dynamically add roles to authorize attribute for controller but for ASP.NET 5 (vNext) In ASP.NET 5, I can not overwrite AuthorizeAttr
Do we even need the custom authorization handler? Won't the code below do the same?
var roles = new[] { "Admin", "Admin2", "Admin3" }; //Get From DB.
options.AddPolicy("CustomRole", policy =>
{
policy.RequireRole(roles);
});
As mike mentioned, you need policies. Here is one implementation.
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
protected override void Handle(Microsoft.AspNet.Authorization.AuthorizationContext context, CustomRoleRequirement requirement)
{
var roles = new[] { "Admin", "Admin2", "Admin3" }; //Get From DB.
var userIsInRole = roles.Any(role => context.User.IsInRole(role));
if (!userIsInRole)
{
context.Fail();
return;
}
context.Succeed(requirement);
}
}
And in the ConfigureServices method in startup.cs
services.ConfigureAuthorization(options =>{
options.AddPolicy("CustomRole", policy => policy.AddRequirements(new CustomRoleRequirement()));
});
And you need to provide the autorize attribute in the controller like this.
[Authorize(Policy = "CustomRole")]
Source: https://forums.asp.net/post/5975557.aspx
Hope it helps.