Search code examples
javajakarta-eejaasservlet-3.0

How to handle session timeout when using Servlet 3.0 programmatic security


Regarding Servlet 3.0 programmatic security, when a session times out there is no way to invoke HttpServletRequest#logout().

Does the user remain logged into JAAS?

If so, what is best practice to handle logging out of JAAS after session times out?

How does the container handle the user's subsequent request to login again and create a new session after session timeout?

As an aside, what are the pros and cons of using the following three approaches to handle session timeout when using Servlet 3.0 programmatic security:

  1. HttpSessionListener#sessionDestroyed()
  2. Make the @ManagedBean @SessionScoped LoginManager implement HttpSessionBindingListener and do something in valueUnbound.
  3. Annotate a method in LoginManager with @PreDestroy.

Any other suggested approaches/ best practices advice would surely be appreciated.


Solution

  • There is a statement somewhere in the Servlet specification to the effect that session invalidity corresponds precisely to the state where there is no Principal in it. This is the key. logout() and timeout both invalidate the session, and invalidating the session removes the Principal from it, and all its value bindings.

    All that JAAS really does is allow LoginModules to accumulate Principals in a Subject, both for the user and his roles. All that the JAAS logout() method really needs to do is clear the Subject of the Principals that were added by the same module's login(), or more probably commit(), method, and this is really just for total security if you have added things like private credentials to the Subject. As logout() won't be executed by the same instance as login()/commit(), that removal has to be based on principal class rather than on an internal collection of principals.

    The JAAS logout() isn't called when the session expires, but as the Principal is removed from the session that shouldn't really matter to anybody.

    If you want to track session termination for some other reason, e.g. logging, make your user bean a session binding listener and log the termination as a logout in the valueUnbound() method: this is 100% reliable in my experience.

    To answer your other questions, there isn't such a state as 'logged in to JAAS': JAAS provides a login/logout service to the container, not to itself; and a new login is a new login, into a new session, whether or not the previous one expired.