EN
Spring Boot 2.x - change session cookie id value length (JSESSIONID length in Tomcat server)
5
points
In this short article, we would like to show how to change the default JSESSIONID
cookie value length in Spring Boot 2.x.
Note: the below configuration was tested with default Spring Boot 2 application configuration where Tomcat server is used.
Quick solution:
package com.example.config;
import org.apache.catalina.Context;
import org.apache.catalina.Manager;
import org.apache.catalina.SessionIdGenerator;
import org.apache.catalina.session.StandardManager;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TomcatConfig {
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> servletContainerCustomizer() {
return (TomcatServletWebServerFactory container) -> {
container.addContextCustomizers((Context context) -> {
Manager manager = context.getManager();
if (manager == null) {
context.setManager(manager = new StandardManager()); // if not defined before
}
SessionIdGenerator generator = manager.getSessionIdGenerator();
// 32 bytes requires 64 characters to encode cookie value
// by default, used session is length is 16 bytes
generator.setSessionIdLength(32);
});
};
}
}
Example cookies:
Hint: since you will change session id length, the effect will be visible only on the newly created sessions - it means the old sessions should be removed or expired to get effect.