Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invalidate user session on inactivity in a stateless server?

I'm building a stateless RESTful server backend in Java, that will be used by an AngularJS frontend. Since it should be stateless, I don't create sessions but generate access tokens, more precisely JSON web tokens, the client has to present on every request.

The tokens contain an "expires" field which acts as an absolute expiration date. However, I would like to have an additional expiration on user inactivity. So I would define the access token to be valid as long as 24 hours if the user is active once every 30 minutes.

I could implement this by writing something to the database on every request and verify the time between requests, but this seems a lot of work for something that was working out of the box when using application server's session management.

like image 601
Tim Büthe Avatar asked Nov 24 '25 15:11

Tim Büthe


1 Answers

To be 100% stateless on server side you need to push state logic to the client. The solution is:

  • issue JWT with 2 expiry dates (one for session - 30 minutes, second for refresh - 24h)
  • implement getting new token for the same user with previous token (new token has new expiry date for session, but the same for refresh)
  • reject requests when whatever expiry date is exceeded
  • implement "clever" javascript client that is able to get new tokens while user is clicking UI; you can optimize it, by skipping refresh requests when token has more than 25 minutes to expiration date
like image 63
Piotr Bochynski Avatar answered Nov 28 '25 16:11

Piotr Bochynski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!