简体   繁体   中英

Set authorize attribute for Custom policy for all controller and Actions at global

I am new to .Net / ASP.NET development and I am trying to use custom policy that I would like to add at the global level so that I don't have to add [ Authorize ] attribute in each controller for a policy I built.

I created a policy called SuperAdminUsers and uses custom requirement from UserNamesRequirement which I would like to set it at the global level, that way all SuperAdminUsers will have access to all controller and actions.

Below is my policy that I have created in startup.cs file.

services.AddAuthorization(
        option =>
        {
            option.AddPolicy("Admin", policy => policy.RequireRole("DOMAIN\\GroupName"));
            option.AddPolicy("SuperAdminUsers", policy => policy.Requirements.Add(new UserNamesRequirement("DOMAIN\\USER1", "DOMAIN\\USER2"))
        }
);
// Add Custom filters
services.AddMvc(
    config =>
    {
        var policy = new AuthorizationPolicyBuilder();
        policy.Requirements.Add(new UserNamesRequirement("DOMAIN\\USER1"));
                policy.Build();
                config.Filters.Add(new AuthorizeFilter(policy));
    }
);

In config.Filters above, I get an error shown in below screenshot:

在此输入图像描述

Here is my Customer Requirement and Handle classes:

public class UserNamesRequirement : IAuthorizationRequirement
{
    public UserNamesRequirement(params string[] UserNames)
    {
        Users = UserNames;
    }
    public string[] Users { get; set; }
}

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserNamesRequirement requirement)
{
        // var userName = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
        var userName = context.User.Identity.Name;

        if (requirement.Users.ToList().Contains(userName))
            context.Succeed(requirement);
        return Task.FromResult(0);
}

UPDATE 1:

Update start up file with below code, but still unable to authorize.

services.AddMvc
        (
            config =>
            {
                var policyBuilder = new AuthorizationPolicyBuilder();
                policyBuilder.Requirements.Add(new UserNamesRequirement("DOMAIN\\USER1", "DOMAIN\\USER2"));
                var policy = policyBuilder.Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            }
        );

Controller I am trying to access:

[Authorize(Policy = "Admins")]
[Authorize(Policy = "SuperAdminUsers")]
public class OperatingSystemsController : Controller
{
    private readonly ServerMatrixDbContext _context;

    public OperatingSystemsController(ServerMatrixDbContext context)
    {
        _context = context;    
    }

    // GET: OperatingSystems
    public async Task<IActionResult> Index()
    {
        return View(await _context.OperatingSystems.ToListAsync());
    }
}

Here is what I see it in str output log file:

NOTE: I removed real domain and username.

Application started. Press Ctrl+C to shut down.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost/demo/OperatingSystems/Create  
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
      Authorization was successful for user: DOMAIN\USER1.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: DOMAIN\USER1.
warn: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]

Any help is really appreciated.

A filter is one way to set the authorization attribute for all controllers and actions. For instance, here is policy that requires a specific user name.

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireUserName("DOMAIN\\USERID")
                     .Build();

    config.Filters.Add(new AuthorizeFilter(policy));
});

The error you're receiving happens because the AuthorizationFilter constructor expects a policy not a policyBuilder . Here is your code with the variable names changed for greater clarity.

services.AddMvc(config =>
{
    var policyBuilder = new AuthorizationPolicyBuilder();
    policyBuilder.Requirements.Add(new UserNamesRequirement("DOMAIN\\USER1"));

    // this will NOT work
    policyBuilder.Build();
    config.Filters.Add(new AuthorizeFilter(policyBuilder));

    // this will work
    var policy = policyBuilder.Build();
    config.Filters.Add(new AuthorizeFilter(policy));

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM