Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add roles to authorize attribute for controller in ASP.NET 5

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.

like image 746
congtinit Avatar asked Jan 07 '23 09:01

congtinit


2 Answers

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.

like image 54
Anuraj Avatar answered Jan 14 '23 13:01

Anuraj


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);            
                    });
like image 25
user3482465 Avatar answered Jan 14 '23 12:01

user3482465