How can I disable an authorization filter for a specific GET handler in Web API?
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. That custom filter derives from AuthorizationFilterAttribute
. The class also have two another attributes: OverrideAuthentication
and EnableCors
.
I tried AllowAnonymous
attribute but it doesn't.
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. Now AllowAnonymous
will be to do its magic.
[Route("api/accounts/{accountNumber}/GetX")]
[AllowAnonymous]
[OverrideAuthorization]
[HttpGet]
public HttpResponseMessage GetX(string accountNumber)
{
// Process
// ..
// ..
}