Languages
[Edit]
EN

Spring Boot 2.x - change session cookie id value length (JSESSIONID length in Tomcat server)

5 points
Created by:
Frank-van-Puffelen
379

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:

Changed JSESSIONID cookie value length to longer - Spring Boot 2.x.
Changed JSESSIONID cookie value length to longer - Spring Boot 2.x.

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.

 

See also

  1. Tomcat - set JSESSIONID length / set session id length 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join