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.
But the in Web API you will get a response with status code 200 (OK) with the response body with the following message.
And also as API developers we do not prefer this default behavior.
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.
Using cookie authentication middleware with Web API and 401 response codes:
What I’ve provided is a more generic solution built into the framework itself.