.Net core Authorize attribute in inherited controller

gon*_*ong 4 claims-based-identity asp.net-core

I am having some trouble with Authorization policies. I have a baseWebApiController with an action

[HttpDelete("{id}"), Authorize(Policy = "Administrator")]
public virtual async Task<IActionResult> Delete(int id) {}
Run Code Online (Sandbox Code Playgroud)

But in a certain controller which inherits from the above I want to give access to users also, with a policy like:

[HttpDelete("{id}"), Authorize(Policy = "All")]
public override Task<IActionResult> Delete(int id){}
Run Code Online (Sandbox Code Playgroud)

It seems regular users cannot access this action. Do I have to search further for errors in my policy configuration, or since the controller is inherited,m it's attributes are neglected?

Thanks

pok*_*oke 6

AuthorizeAttribute是一个继承的属性,允许多次应用。

\n\n

这意味着当继承已有的方法时AuthorizeAttribute,该方法将被继承。因此子类中的最终函数定义如下所示:

\n\n
[Authorize(Policy = "Administrator")]\n[Authorize(Policy = "All")]\npublic override Task<IActionResult> Delete(int id)\n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,该路线现在有两项政策。这是一个问题,因为政策的设计是累积性的。因此,所有策略都必须通过才能使身份验证成功。

\n\n

当然,这对您不起作用,因为您实际上想从基类中清除 \xe2\x80\x9c 原始策略。但这是不可能的,因此您必须从基类中删除该策略,并且可能为这些策略引入第二个仅管理员类。

\n\n

这里的普遍问题是你的政策设计似乎是基于角色的。您正在使用策略,但实际上您正在检查那里的角色。相反,您应该考虑处理要求:例如,要删除某些内容,用户需要满足 \xe2\x80\x9cDeletionAllowed\xe2\x80\x9d 要求。这允许建立更细粒度的政策体系。最大的好处是什么?要求处理程序是分离的:因此,一个能够满足要求的处理程序就足以通过它。

\n