Weird AJAX redirect 401 issue with IIS Weird AJAX redirect 401 issue with IIS ajax ajax

Weird AJAX redirect 401 issue with IIS


Ahhhh, you know when you don't think about something for a while and you get hit with sudden inspiration... Well it happened last night and I found this little nugget put in place to "fix" MVC's insistance on redirecting AJAX requests when authentication fails...

protected void Application_EndRequest(){    var context = new HttpContextWrapper(Context);    // MVC retuns a 302 for unauthorized ajax requests so alter to request status to be a 401    if (context.Response.StatusCode == 302 && context.Request.IsAjaxRequest() && !context.Request.IsAuthenticated)    {           context.Response.Clear();        context.Response.StatusCode = 401;    }}

And, unsuprisingly, context.Request.IsAuthenticated is always false as it appears to get reset by the redirect .

Updated this, with a little help from Branislav Abadjimarinov's blog post on the subject.

protected void Application_EndRequest(){    var context = new HttpContextWrapper(Context);    // MVC returns a 302 for unauthorized ajax requests so alter to request status to be a 401    if (context.Response.StatusCode == 302 && context.Request.IsAjaxRequest())    {        //Unfortunately the redirect also clears the results of any authentication        //Try to manually authenticate the user...        var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];        if (authCookie != null)        {            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);            if (authTicket != null && !authTicket.Expired)            {                var roles = authTicket.UserData.Split(',');                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);            }        }        if (!context.Request.IsAuthenticated)        {            context.Response.Clear();            context.Response.StatusCode = 401;        }    }}

And it all works as expected.

Only question is should I remove this question?


Take a look at this Cannot handle 302 redirect in ajax and why? [duplicate], it looks like the web browser sees the Found-302 and performs an action on it.