4

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.

7
  • What if you remove [OverrideAuthentication] and [AccountAuthorization] from the controller? Commented Apr 11, 2016 at 21:12
  • 2
    Possible duplicate of AllowAnonymous not working with Custom AuthorizationAttribute Commented Apr 11, 2016 at 21:15
  • See this too, you may be able to allow anonymous on specific URLs in the web api.. stackoverflow.com/questions/14588397/… Commented Apr 11, 2016 at 21:18
  • @MaxSorin: Still doesn't works. Commented Apr 11, 2016 at 21:26
  • Then you are intercepting the request elsewhere that is not visible to us. Commented Apr 11, 2016 at 21:42

1 Answer 1

3

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     
    // ..
    // ..
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.