I have a scenario where I have to handle authentication of ajax requests using "Forms Authentication". Based on some search and help from my earlier stackoverflow post, I had decided to use the method described at here.
The idea is to send back a 401 response for unauthenticated requests, and then handle that in the AJAX error handler. So I have an AJAX error handler in my ASP.net MVC3 Layout page that redirects the browser to the login page when it receives 401 response on unauthenticated ajax requests. Here is the ajax error handler.
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == "401") {
window.location.replace(loginUrl);
}
....
});
This all works well on my local IIS 7.5 Server. But on the server where my site is hosted, unfortunately, I get a basic authentication popup on unauthenticated ajax requests (for example session timed out), before the AJAX error handler runs and redirects the browser to the login page. When I cancel the "Authentication Required" popup by pressing the Cancel button, the AJAX error handler then runs and I am redirected to the login page.
So, why does the browser show the authentication popup before running the AJAX error handler?
Edit: The Hosting Server is running IIS 6.
as Softlion said
This is a common question with an easy answer. the 401 is transformed into a 302 to the login >page by the .net authorization module. The browser never see the 401 only the 302.
if you are using .net 4 and later, you use code below
HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
it work's fine for me.
This is a common question with an easy answer. the 401 is transformed into a 302 to the login page by the .net authorization module. The browser never see the 401 only the 302.
Of course this is not playing nicely with ajax calls.
The best solution i tryed and i'm currently using involve writing a new attribute which is catching 401 and tranform it into ... 409 which is catched by the jquery ajax handler.
It is part of a paid product so i can not give any code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With