Posted tagged ‘MVC5’

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

April 15, 2016

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.