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
Basically, ajax request as well as synchronous request sends your document cookies automatically.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With