简体   繁体   English

ASP.NET Web API覆盖处理程序的授权过滤器

[英]ASP.NET Web API Override authorization filter for a handler

How can I disable an authorization filter for a specific GET handler in Web API? 如何在Web API中禁用特定GET处理程序的授权过滤器?

There's a custom authorization filter on the class level but for one of the methods I need to have no security. 在类级别上有一个自定义授权过滤器,但对于其中一种方法,我需要没有安全性。 I tried applying [AllowAnonymous] attribute but it still runs through the higher-level filter and fails. 我尝试应用[AllowAnonymous]属性,但它仍然通过更高级别的过滤器运行并失败。 That custom filter derives from AuthorizationFilterAttribute . 该自定义过滤器派生自AuthorizationFilterAttribute The class also have two another attributes: OverrideAuthentication and EnableCors . 该类还有另外两个属性: OverrideAuthenticationEnableCors

I tried AllowAnonymous attribute but it doesn't. 我尝试过AllowAnonymous属性,但事实并非如此。

Sample code: 示例代码:

[EnableCors(origins: "*", headers: "*", methods: "*")]
[OverrideAuthentication]
[AccountAuthorization]
public class AccountsController : ApiController
{

    [Route("api/accounts/{accountNumber}/GetX")]
    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage GetX(string accountNumber)
    {
        HttpResponseMessage response = null;
        IEnumerable<string> apiKey;
        if (!Request.Headers.TryGetValues("X-ApiKey", out apiKey) || apiKey.Count() != 1 || apiKey.First() != API_KEY)
        {
            throw new HttpResponseException(HttpStatusCode.Forbidden);
        }

        // Process
        // ..
        // ..

        return response;
    }
}

EDIT: The linked answer doesn't explain what's the solution. 编辑:链接的答案没有解释什么是解决方案。

Figured it out at last. 终于搞清楚了。

Since there is already an existing custom authorization filter on the class/controller level, therefore, to override a specific action handler (the method) and have it work without any authorization filters, we need to override the filter at the controller/class level. 由于在类/控制器级别上已经存在自定义授权过滤器,因此,要覆盖特定的操作处理程序(方法)并使其在没有任何授权过滤器的情况下工作,我们需要在控制器/类级别覆盖过滤器。 So adding the OverrideAuthorization filter did the trick. 因此添加OverrideAuthorization过滤器就可以了。 Now AllowAnonymous will be to do its magic. 现在AllowAnonymous将发挥其魔力。

[Route("api/accounts/{accountNumber}/GetX")]
[AllowAnonymous]
[OverrideAuthorization]
[HttpGet]
public HttpResponseMessage GetX(string accountNumber)
{
    // Process     
    // ..
    // ..
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM