Intercepting the HTTP Session Expiry & SpringSecurity


Staff member
Here's a little tip for when you need to discover when a users session expires and perform any cleanup for the current logged in user.

You need a listener class that implements HttpSessionListener such as :

public class ExpiringSessionEventListener implements  HttpSessionListener {

     private static final Log log = LogFactory.getLog(ExpiringSessionEventListener.class);

     public void sessionCreated(HttpSessionEvent event) {
"Session created");

     public void sessionDestroyed(HttpSessionEvent event) {

"Session destroyed");


    void cleanUpUser(HttpSessionEvent event) {
      SecurityContext sCtx = event?.session?.getAttribute("SPRING_SECURITY_CONTEXT")
      if (sCtx) {
        Authentication auth = sCtx.authentication
        Long userId =
        // now you have the user ID you can perform any cleanup code you need to for that user

And you need to define your listener in web.xml - if you don't have web.xml Grails will create it for you when you issue the command "grails install-templates"

Your entry should reflect your listeners full class name e.g.


Note this approach has been created for use with Grails 1.3.7