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 toeach
ajax call'scompletion handler
to detect the redirection-to-login-page response andimperatively
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