在一个.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(...) {...}
主要思想是声明一次政策。最近的两个代码块是伪代码,有谁知道类似概念的实用解决方案?
答案 0 :(得分:1)
您可以实现自己的IAuthorizationFilter
自定义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();
}
}
}
自定义CustomAuthorizeAttribute
public class CustomAuthorizeAttribute : TypeFilterAttribute
{
public CustomAuthorizeAttribute(int input) : base(typeof(CustomAuthorize))
{
Arguments = new object[] { input };
}
}
使用
[CustomAuthorizeAttribute(1)]
public IActionResult About()