4

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.

Community
  • 1
  • 1
congtinit
  • 113
  • 2
  • 7
  • In MVC6 (vNext), you can write an authorization policy that looks at the user role and does whatever it wants - e.g., compare it against a dynamically generated list. See https://github.com/blowdart/AspNetAuthorization-Samples/blob/master/src/AspNetAuthorization/Authorization/Over18.cs for an example of a policy. – Mike Wasson Oct 12 '15 at 19:54

2 Answers2

8

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.

Anuraj
  • 18,859
  • 7
  • 53
  • 79
2

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);            
                    });