Configure session timeout for Grails 3 applications

Grails 3 is built on top of Springboot and utilizes servlet 3 features so there is no web.xml file where you can configure the session timeout. Below is an example of how to configure session timeout for Grails 3 applications.

Configure session timeout for Embedded tomcat

During development, grails application is run inside an embedded tomcat container which is controlled by spring boot. The session timeout can be configured using below setting in application.yml

server:
   session:
      timeout: 3600

Configure session timeout for standalone tomcat

The above configuration in application.yml works good for development environment. However it will have no effect when the war is deployed to a standalone tomcat. The other option is to create a HttpSessionListener and set the maxInActiveInterval from sessionCreated event. 

@WebListener
class SessionTimeoutListener implements HttpSessionListener {

	@Override
	void sessionCreated(HttpSessionEvent event) {
		event.session.setMaxInactiveInterval(1000)
	}

	@Override
	void sessionDestroyed(HttpSessionEvent se) {

	}
}

The listener class is annotated with @WebListener annotation so it will be automatically discovered by container.

Global sesssion timeout configuration for all applications deployed to tomcat.

All applications deployed to tomcat inherits the configuration from $CATALINA_BASE/conf/web.xml so any configuration put in this file will apply to every application.

<session-config>
  <session-timeout>60</session-timeout>
</session-config>

 

Note: the session-timeout value configured in web.xml is in minutes whereas session.setMaxInActiveInterval() is in seconds.