在 aspnet core 中使用 Policy 覆盖 AuthorizeAttribute

Override AuthorizeAttribute with Policy in aspnet core

Using ASP.NET 5 我已经实现了一个 policy,我希望将其应用于控制器中的大多数但不是所有方法。对于其他方法,我只想验证当前用户是否已通过身份验证。有没有办法做到这一点,或者我是否需要将 [Authorize(Policy="MyPolicy")] 分别添加到每个方法,而不是添加到 class?

例如我想要这个(但我有更多的方法应该被政策授权):

[ApiController]
[Authorize(Policy="MyPolicy")]
[Route("api/DoStuff")]
public class MyController : ControllerBase
{ 

    // this one is authorized by MyPolicy, based on the class Authorize attribute
    [HttpGet("foo")]
    public GetFoo() 
    {
    }

    // this one is authorized by MyPolicy, based on the class Authorize attribute
    [HttpGet("bah")]
    public GetBah() 
    {
    }

    // This one I just want to check they're authenticated, not enforce "MyPolicy"
    [Authorize] 
    [HttpGet("anybody")]
    public GetForAnybody() 
    {
    }
}

我认为在 .net webapi 中我可以用 OverrideAuthorizationAttribute 做这种事情。

据我所知,Asp.netCore不支持OverrideAuthorizationAttribute,也不建议覆盖controller授权属性。您可以查看 this thread.

因此,在您的情况下,我认为最好的解决方法是更改​​您的代码,如下所示:

[ApiController]
[Authorize]
[Route("api/DoStuff")]
public class MyController : ControllerBase
{ 

    // this one is authorized by MyPolicy, based on the class Authorize attribute
    [HttpGet("foo")]
    [Authorize(Policy="MyPolicy")]
    public GetFoo() 
    {
    }

    // this one is authorized by MyPolicy, based on the class Authorize attribute
    [HttpGet("bah")]
    [Authorize(Policy="MyPolicy")]
    public GetBah() 
    {
    }

    // This one I just want to check they're authenticated, not enforce "MyPolicy"
    //[Authorize]   //since the controller already set the Authorize attribute, there is no need to add it in the action method.
    [HttpGet("anybody")]
    public GetForAnybody() 
    {
    }

    // everybody could access
    [AllowAnonymous]  //By using the `[AllowAnonymous]` attribute, you can restrict the controller and then allow anonymous access to specific actions.
    [HttpGet("everybody")]
    public GetForEverybody() 
    {
    }
}