【问题标题】:ASP.NET Web API Override authorization filter for a handler处理程序的 ASP.NET Web API 覆盖授权过滤器
【发布时间】:2016-08-02 05:45:00
【问题描述】:

如何禁用 Web API 中特定 GET 处理程序的授权过滤器?

在类级别有一个自定义授权过滤器,但对于其中一种方法,我需要没有安全性。我尝试应用 [AllowAnonymous] 属性,但它仍然通过更高级别的过滤器并失败。该自定义过滤器派生自AuthorizationFilterAttribute。该类还有另外两个属性:OverrideAuthentication 和 EnableCors。

我尝试了AllowAnonymous 属性,但没有。

示例代码:

[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;
    }
}

编辑:链接的答案没有解释解决方案是什么。

【问题讨论】:

标签: c# asp.net authorization asp.net-web-api2 authorize-attribute


【解决方案1】:

终于想通了。

由于在类/控制器级别已经存在自定义授权过滤器,因此,要覆盖特定的操作处理程序(方法)并使其在没有任何授权过滤器的情况下工作,我们需要覆盖控制器/班级水平。所以添加OverrideAuthorization 过滤器就可以了。现在AllowAnonymous 将发挥它的魔力。

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

【讨论】:

    猜你喜欢
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 2013-04-09
    相关资源
    最近更新 更多