Custom Authorization Filter returns 200 OK during authorization failure in Web API / MVC

Posted on Updated on

This is a very specific and a quick post. In Web APIs sometimes we need to implement custom authorization filter which is extended from AuthorizeAttribute class, this is mainly useful in implementing authorization.

The below code shows how to implement an admin authorization in claims based authentication using ClaimsIdentity

The above code works perfectly in controllers and actions. If you pass ‘true’ to IsAdmin only the authentication requests with the claim IsAdmin true can access the respective controllers or actions.

So when a user who is not an admin tries to access controller / action decorated with the above attribute the client should receive a 401 (Unauthorized) / 403 (Forbidden) reply.

The Problem

But the in Web API you will get a response with status code 200 (OK) with the response body with the following message.

This is not a desirable behavior mainly in APIs because when you make a request from AJAX using any Javascript library, there’s a high probability that they would treat the request as success. You should in cooperate specific client logic to detect this and read the response body JSON message.

And also as API developers we do not prefer this default behavior.

The Solution

The solution is very simple, yet I thought to write a blog on this because in the Internet most of the posts say that this behavior cannot be altered from the API side. But API developers have full control over this behavior. Simply override the HandleUnauthorizedRequest method of the AuthorizeAttribute class.

Now you will get 403 error code as expected with the custom message provided in the Content in the response body.

If it is an MVC application you could do a redirection to the login page.

Advertisements

2 thoughts on “Custom Authorization Filter returns 200 OK during authorization failure in Web API / MVC

    Mark G said:
    August 12, 2015 at 10:04 PM

    Using cookie authentication middleware with Web API and 401 response codes:

    http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/

      Thuru said:
      August 14, 2015 at 4:53 PM

      What I’ve provided is a more generic solution built into the framework itself.

Comments are closed.