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:
xxxxxxxxxx
1
package com.example.config;
2
3
import org.apache.catalina.Context;
4
import org.apache.catalina.Manager;
5
import org.apache.catalina.SessionIdGenerator;
6
import org.apache.catalina.session.StandardManager;
7
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
8
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
9
import org.springframework.context.annotation.Bean;
10
import org.springframework.context.annotation.Configuration;
11
12
13
public class TomcatConfig {
14
15
16
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> servletContainerCustomizer() {
17
return (TomcatServletWebServerFactory container) -> {
18
container.addContextCustomizers((Context context) -> {
19
Manager manager = context.getManager();
20
if (manager == null) {
21
context.setManager(manager = new StandardManager()); // if not defined before
22
}
23
SessionIdGenerator generator = manager.getSessionIdGenerator();
24
// 32 bytes requires 64 characters to encode cookie value
25
// by default, used session is length is 16 bytes
26
generator.setSessionIdLength(32);
27
});
28
};
29
}
30
}
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.