4499

Different response to non-authenticated users and AJAX calls

My ASP MVC (1.0) website has a default login page (based on OpenId - but that shouldn't make a different). It works fine when AuthorizedAttribute is on the Action/Controller.

However, I have AJAX requests coming in as well. Here is what I do with them:

if (Request.IsAjaxRequest()) { if (Request.IsAuthenticated) { // Authenticated Ajax request } else { // Non-authenticated Ajax request. Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Json(new { response = "AUTHENTICATION_FAILED" }); } }

The problem is if I set the Response.StatusCode to Unauthorized, the request is redirected to my login page which is not good for Ajax requests.

Any suggestions for this issue is appreciated.

Answer1:

This is a common problem.

The Authorize attribute returns a Http 401 Unauthorized response. Unfortunately, however if you have FormsAuthentication enabled, the 401 is intercepted by the FormsAuthenticationModule which then performs a redirect to the login page - which then returns a Http 200 (and the login page) back to your ajax request.

The best alternative is to modify your authorization code to return a different Http status code - say 403 - which is not caught by the formsAuthenticationModule and you can catch in your Ajax method.

Answer2:

You can make your own authorize filter that inherent from the framework one, and override the function that write to the response when the user is not authorized, not setting the status code if the request is from ajax. Something like this:

public class MyAutorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) filterContext.Result = new JsonResult() { Data = new { response = "AUTHENTICATION_FAILED" } }; else filterContext.Result = new HttpUnauthorizedResult(); } }

And now on your action use the new attribute

[MyAutorize] public ActionResult myAction() { if (Request.IsAuthenticated) // You should not need to ask this here { // Authenticated Ajax request } else { // Non-authenticated Ajax request. Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Json(new { response = "AUTHENTICATION_FAILED" }); } }

Answer3:

One way of solving this is to add a text to uniquely identify the login page and use it in AJAX call back to redirect to a login page again. Here is a sample code using jQuery global callbacks....

$(document).bind("ajaxComplete", function(event, response, ajaxOptions) { if (response.status == 200 && response.responseText.match(/LOGIN_PAGE_UNIQUE_KEY/)) { self.location = "/web/login?timeout=1"; return false; } });

Recommend

  • Disconnect FB user from using App
  • Payum Bundle : How to change the view of capture action in symfony2
  • How to fetch the file list from gcs?
  • How to return a HashTable from a WebService?
  • yii2 create translated URLs
  • Error when trying to send an email using Gmail API in Java
  • Index.php as custom error page
  • SPARQL date range
  • read values from form post in jquery or javascript
  • Less Conflicting Session Manager for Zope 2
  • Changing Jupyter Notebook start up folder by modifying “start in” not working any more
  • Sending keystrokes/mouse clicks to a Java program with Autohotkey
  • Does Mobilefirst provide a provision to access web services directly?
  • gspread or such: help me get cell coordinates (not value)
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • How to match http request and response using Jersey ContainerRequestFilter and ContainerResponseFilt
  • print() is showing quotation marks in results
  • Custom Tabgroup Appcelerator
  • Play WS (2.2.1): post/put large request
  • $wpdb not working in file of WordPress plugin
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • Installing Hadoop, Java Exception about illegal characters at index 7?
  • Projection media query: browser support and workarounds?
  • Display issues when we change from one jquery mobile page to another in firefox
  • C# - Serializing and deserializing static member
  • Incrementing object id automatically JS constructor (static method and variable)
  • Knitr HTML Loop - Some HTML output, some R output
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • Do create extension work in single-user mode in postgres?
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • Data Validation Drop Down Box Arrow Disappearing
  • Java static initializers and reflection
  • Change div Background jquery
  • Bitwise OR returns boolean when one of operands is nil
  • Is it possible to post an object from jquery to bottle.py?
  • Is there any way to bind data to data.frame by some index?
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?