Cameron Cameron - 2 months ago 6
jQuery Question

Handling AJAX requests if a session has expired

In my app (ASP.NET MVC 3 RAZOR), when a session expires and the user tries to access something, it redirects them to the login page to re-login.

This is fine, but when calling from ajax requests (e.g. if the user has left their screen for a while with no activity), it will load the login form in the ajax request... Which is not what I want to happen.

What is the best way of dealing with this? Ideally I'd like to show a modal if the session has expired so the user can't access other areas. So even if they leave the screen some jQuery will have checked the session and then applied a modal saying 'Session Expired'

How would I do this?

e.g.

if(SESSION HAS EXPIRED) { showModal(); }

Answer

I can see two separate addressable issues here, so I will discuss them each separately.

Login returned as AJAX result:
Rather than just return the login screen, return a message indicating that the session has expired. If your AJAX receives such a message, it knows the user needs to log back in. At this point, you can do something like

window.location = loginpageurlhere;

Alternately, you can check your AJAX response to see if it is an expected response or if it is the login page. If it is the login page, use the above suggestion.

Display dialog if user is inactive for too long:
For this, you need to know how long the user is inactive. You can do this in a couple different ways, one of which is as follows:

  • When the page loads, initialize a variable to use as a countdown.
  • Set a timer that will decrement the counter every time it runs out of time, and then restart.
  • If the counter ever hits zero, display the dialog and have the user log back in.
  • Every time a valid activity occurs (AJAX post or whatever else you may have), reset the counter.

You could use either, of these methods, although if you are concerned about protecting data at an unattended machine, the second method would be best, since you can block the screen and only display the dialog, and it will happen while the user is away, whereas the first method can't do anything until a user actually attempts to perform an action on your page.