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 AuthorizeAttribute class as above post said. So how can I add roles dynamically Controllers in ASP.NET 5 (vNext)
Thanks in advance.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With