相同的策略,但每个操作方法所需的参数不同

Same Policy but different required parameter for each action method

在一个.Net core Webapi 2.1项目中,我有很多操作方法。
所有操作方法都应根据相同的策略(名为 FooPolicy)授权,但需要的参数不同。
基于 Microsoft 的文档:Policy-based-Authorization 一种方法是根据不同的输入参数声明大量策略:

services.AddAuthorization(options =>
{
    options.AddPolicy("FooPolicy1", policy =>policy.Requirements.Add(new FooRequirement(1)));
    options.AddPolicy("FooPolicy2", policy =>policy.Requirements.Add(new FooRequirement(2)));
    options.AddPolicy("FooPolicy3", policy =>policy.Requirements.Add(new FooRequirement(3)));
    //... May be 30 more same policies here ...
});

正如我之前提到的,new FooRequirement(diffArgs) 中只有不同的部分。此解决方案的另一个挑战是将每个 FooPolicy 添加到其相应的操作方法上,您可能会错过几个主题:

[Authorize(Policy = "FooPolicy1")]
public IActionResult ActionMethodFoo1(...) {...}

[Authorize(Policy = "FooPolicy2")]
public IActionResult ActionMethodFoo2(...) {...}

[Authorize(Policy = "FooPolicy3")]
public IActionResult ActionMethodFoo3(...) {...}
...List still goes on...

是否有类似以下的解决方案: 声明一次策略但将其用于 FooRequirement 的不同实例(类型为 IAuthorizationHandler)?像这样:

services.AddAuthorization(options =>
{
    options.AddPolicy("FooPolicy", policy =>policy.Requirements.Add(?));
});

关于动作方法:

[Authorize(Policy = "FooPolicy", required = new FooRequirement(1))]
public IActionResult ActionMethodFoo1(...) {...}

[Authorize(Policy = "FooPolicy", required = new FooRequirement(2))]
public IActionResult ActionMethodFoo2(...) {...}

[Authorize(Policy = "FooPolicy", required = new FooRequirement(3))]
public IActionResult ActionMethodFoo3(...) {...}

主要思想是声明一次政策。最近的两个代码块是伪代码,有没有人知道具有类似概念的实际解决方案?

您可以实现自己的 IAuthorizationFilter

  1. 自定义IAuthorizationFilter

    public class CustomAuthorize : IAuthorizationFilter         
     {
            private readonly int _input;
    
    public CustomAuthorize(int input)
    {
        _input = input;
    }
    
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //custom validation rule
        if (_input == 1)
        {
            context.Result = new ForbidResult();
        }
    }
    }
    
  2. 自定义 CustomAuthorizeAttribute

    public class CustomAuthorizeAttribute : TypeFilterAttribute
    {
    public CustomAuthorizeAttribute(int input) : base(typeof(CustomAuthorize))
    {
        Arguments = new object[] { input };
    }
    }
    
  3. 使用

    [CustomAuthorizeAttribute(1)]
    public IActionResult About()