Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

distinguish between session timeout and session explicit (programmatic) invalidation

I have an HttpSessionListener. Is there a way, inside its sessionDestroyed method to distinguish between the following cases:

  • the session was destroyed because the session-timeout configured in the web.xml was exceeded
  • the session was destroyed programmatically by the the application calling HttpSession#invalidate

My use case is that I have a Single Sign On (SSO) arrangement between a number of applications and I want a global single sign off when one of the applications participating in the SSO arrangement explicitly logs off but not when its session times out, hence the need to distinguish between the two cases. I guess a way would be for the application to set some flag in the session object just prior to calling HttpSession#invalidate. The HttpSessionListener would then examine the session object and if that flag is found it would know this was a programmatic logout. If not, it was a container logout. Would that make sense and / or is there a better way?

like image 503
Marcus Junius Brutus Avatar asked Sep 05 '26 23:09

Marcus Junius Brutus


1 Answers

You can use HttpSession#getLastAccessedTime() to obtain the timestamp of the last request sent by the client associated with the session. Then you can just do the math with help of HttpSession#getMaxInactiveInterval() and the current timestamp.

long lastAccessedTime = session.getLastAccessedTime();
long timeoutInMillis = TimeUnit.SECONDS.toMillis(session.getMaxInactiveInterval());
long now = System.currentTimeMillis();

boolean sessionHasBeenTimedout = (now - timeoutInMillis > lastAccessedTime);
// ...
like image 191
BalusC Avatar answered Sep 08 '26 02:09

BalusC



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!