为所有控制器的自定义策略和全局的操作设置authorize属性

时间:2016-10-21 22:56:40

标签: c# asp.net-core asp.net-core-mvc

我是.Net / ASP.NET开发的新手,我正在尝试使用我想在全局级别添加的自定义策略,这样我就不必添加[Authorize]属性了我建立的政策的每个控制器。

我创建了一个名为SuperAdminUsers的政策,并使用UserNamesRequirement中的自定义要求,我希望将其设置为全局级别,这样所有SuperAdminUsers都可以访问所有控制器和动作。

以下是我在startup.cs文件中创建的政策。

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

在上面的config.Filters中,我收到了以下屏幕截图中显示的错误:

enter image description here

这是我的客户要求和处理类:

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

更新1:

使用以下代码更新启动文件,但仍无法授权。

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

我想要访问的控制器:

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

以下是我在str输出日志文件中看到的内容:

  

注意:我删除了真实域名和用户名。

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]

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

过滤器是为所有控制器和操作设置授权属性的一种方法。例如,这是需要特定用户名的策略。

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

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

您收到的错误是因为AuthorizationFilter构造函数需要policy而不是policyBuilder。以下是更改变量名称的代码。

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

});