Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login screen in ajax result - Asp.net Mvc

When you're using the asp.net membership and you have the [Authorize] tag on a controller / Action, sometimes when you get back from getting coffee / a walk whatever, you have been logged out of the site. When you click a button or link that invokes an Ajax call, the returned html is not what you requested but the login screen, which then get rendered somewhere on the page (if you use $("placeholder").html(result)).

Is there anyway to detect this in jQuery ? As it is legit html you don't get an error, but it's not something you want to have happen ofcourse.

like image 481
Morph Avatar asked Mar 20 '09 21:03

Morph


2 Answers

One thing that you could do is client-side session timeout detection. Set up a timer that will expire shortly before your actual session expires. Have the timer pop-up a dialog indicating that the session is about to expire and let the user have the opportunity to renew it (send back an AJAX request to refresh the session timer). Have another timer on the dialog that will expire before the time remaining on the actual session runs out. If this timer fires, then reset the href of the page to the logout url and log the user out. Obviously, the timers will need to be reset by user activity on the page -- ajax requests, etc.

like image 155
tvanfosson Avatar answered Oct 02 '22 04:10

tvanfosson


tvanfosson's client-side session timeout approach works very nicely, actually - I've been impressed by several sites that I've returned to after lunch and found they've automatically redirected back to the login page.

Another approach could be as follows:

You send an Ajax request to (say) /Account/Details, but your login cookie has expired, so you're not allowed to see that; the controller returns /Security/Login instead.

If your controller returns the login view instead of the requested page, have you considered setting the response code to 401 Not authorized instead of 200 OK?

You'd then need to modify your Ajax callback to inspect the status code of the Ajax response, and if it's a 401 Not authorized, you can respond accordingly - redirect to the login page, show a pop-up login box, or just an error message saying "sorry, you need to log in again"

like image 29
Dylan Beattie Avatar answered Oct 02 '22 06:10

Dylan Beattie