Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response code 401 triggering basic authentication before the jquery ajax error handler

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.

like image 798
Jatin Avatar asked Jan 09 '12 14:01

Jatin


2 Answers

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.

like image 153
reZa Avatar answered Sep 19 '22 19:09

reZa


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.

like image 35
Softlion Avatar answered Sep 21 '22 19:09

Softlion