Authenticated web services calls with Asp.Net MVC
I’ve been encountering a problem as of late. I’m creating a lot of “Single Page Pattern” web applications. This means you load the page once, then handle everything else via web service calls.
And if you have ever worked on web applications you should be familiar with the “user went to lunch” issue (session timeout). User leaves for an hour, comes back to your web page, and expects it to continue working. Unfortunately the session timed out, and now you have to refresh a bunch o’ crap. Another version of the problem, the “.ASPXFORMSAUTH” cookies gets deleted. Either way, your web site stop just working and the user blames you.
The fix is to have the user log in again. Normally this is simple, when the user does something, then the page is refreshed and redirected to the login page (as assigned in the web.config). That is the standard web model. Unfortunately it does not work in this case.
Web services complicate things. When inside a web method request, redirects do not work, and even worse if you are using JQuery “load” method (which loads html directly into an element), then you get the login page inside of a div. But more often, your web client code is expecting JSON, and will be getting html (an error page or the login page).
So my current solution it to wrap up the JQuery AJAX methods with my own methods. This way I can check the users authentication (another web method). If I see the user is not logged in, I redirect to the login page. The other web method is killed via the page redirect.
Here is my wrapper:
Now with the wrapper in place I switch my $.ajax, $.get, $.post calls to ajax.ajax, ajax.get, ajax.post. All the parameters should stay the same.
Now the web method, IsAuthenticated, is about as simple as you can get: