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

前端 未结 2 1332
感动是毒
感动是毒 2021-01-06 09:46

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

相关标签:
2条回答
  • 2021-01-06 10:16

    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);            
                        });
    
    0 讨论(0)
  • 2021-01-06 10:28

    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.

    0 讨论(0)
提交回复
热议问题