Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefully handle login expiration for an Ajax call?

My web application is made up of a lot of Ajax calls to server side RESTful APIs. Each time a customer login my site, the login page will get a JWT (JSON Web Token) token from server and store it as a cookie on client side. (I choose to store it as cookie because it is the only way to let the browser send it automatically and it is said to be safer than HTML5 Web Storage). There's a field in the token describing the token's expiration date. For each Ajax call, the token is sent along for authentication.

If client stays on my page for long, the token can expire. And the server will detect it when client making the next HTTP request (not just REST call). I use a servlet filter to intercept all HTTP requests and check the token for expiration. If the token expired, a redirection-to-login-page response will be sent.

But there's a problem about the above approach: "How to gracefully handle the redirection-to-login-page response on client side?"

  • For non-Ajax originated HTTP request, I can rely on browser to handle the redirection-to-login-page response and make page jump automatically.

  • For Ajax originated HTTP request, it seems I need to add extra logic to each ajax call's completion handler to detect the redirection-to-login-page response and imperatively make the page jump .

Or am I totally on a wrong way?

Some refs:

JWT (JSON Web Token) automatic prolongation of expiration

Which authentication strategy should I use for my API?

Implicit & Explicit authentication

ADD 1:

It seems the browser will handle the 302 redirection transparently. So maybe I can just return a 302 redirection to the login page, be it for a ajax call or a plain page visit. I will try and respond later.

From here:

If the response is an HTTP redirect (status code 301, 302, 303 or 307), then it MUST be transparently followed (unless it violates security or infinite loop precautions). Any other error (including a 401) MUST cause the object to use that error page as the response.

Catching 302 FOUND in JavaScript

How to manage a redirect request after a jQuery Ajax call

like image 639
smwikipedia Avatar asked Dec 17 '15 02:12

smwikipedia


People also ask

Do AJAX calls pass cookies?

Basically, ajax request as well as synchronous request sends your document cookies automatically.

Are AJAX calls slow?

In my app, there are a lot of ajax calls. A user may do 50 ajax calls per session, so speed is very important. The ajax call queries the database and returns a list of records.


1 Answers

For exactly this reason, web APIs should not respond with 302 redirect, but with 401 unauthorized when the token has expired.

Web applications should return 302 responses as they are always meant to be consumed by browser like agents. For more information see also my answer here.

like image 175
MvdD Avatar answered Oct 25 '22 05:10

MvdD