Returning 401 HTTP Status Code on Authentication Failure in MVC 5 Web API’s

Was experiencing a problem that my AJAX requests were not receiving any 401 errors.

Turns out the security pipeline in OWIN and MVC 5 has changed and a custom filter attribute was no longer returning 401 and 403 status codes. Instead it returns a 200 status code and inserting the following information in the header.

X-Responded-JSON: {"status":401,"headers":{"location":"http:\/\/localhost:59540\/Account"}}

As a result JQuery does not detect the error and simply did nothing. Fortunately this great article by Kevin Junghans helped to solve this problem.

After reading this article I discovered the following the OWIN help:

“The LoginPath property informs the middleware that it should change an outgoing 401 Unauthorized status code into a 302 redirection onto the given login path. The current url which generated the 401 is added to the LoginPath as a query string parameter named by the ReturnUrlParameter. Once a request to the LoginPath grants a new SignIn identity, the ReturnUrlParameter value is used to redirect the browser back to the url which caused the original unauthorized status code.

If the LoginPath is null or empty, the middleware will not look for 401 Unauthorized status codes, and it will not redirect automatically when a login occurs.”

Hopefully this saves you the time I spent bumbling around in the deep, dark pit of despair.


Explore posts in the same categories: ASP .NET MVC, Development


You can comment below, or link to this permanent URL from your own site.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: