For the latest stable version, please use Spring Session 3.4.0!spring-doc.cn

Common Configurations

This section contains common configurations that applies to all or most Spring Session modules. It contains configuration examples for the following use cases:spring-doc.cn

Changing How Session IDs Are Generated

By default, Spring Session uses UuidSessionIdGenerator which, in turn, uses a java.util.UUID to generate a session id. There might be scenarios where it may be better to include other characters to increase entropy, or you may want to use a different algorithm to generate the session id. To change this, you can provide a custom SessionIdGenerator bean:spring-doc.cn

Changing How Session IDs Are Generated
@Bean
public SessionIdGenerator sessionIdGenerator() {
    return new MySessionIdGenerator();
}

class MySessionIdGenerator implements SessionIdGenerator {

    @Override
    public String generate() {
        // ...
    }

}

After exposing your SessionIdGenerator bean, Spring Session will use it to generate session ids.spring-doc.cn

If you are manually configuring your SessionRepository bean (instead of using @EnableRedisHttpSession, for example), you can set the SessionIdGenerator directly on the SessionRepository implementation:spring-doc.cn

Setting SessionIdGenerator directly into SessionRepository implementation
@Bean
public RedisSessionRepository redisSessionRepository(RedisOperations redisOperations) {
    RedisSessionRepository repository = new RedisSessionRepository(redisOperations)
    repository.setSessionIdGenerator(new MySessionIdGenerator());
    return repository;
}

Once you have set up Spring Session, you can customize how the session cookie is written by exposing a CookieSerializer as a Spring bean. Spring Session comes with DefaultCookieSerializer. Exposing the DefaultCookieSerializer as a Spring bean augments the existing configuration when you use configurations like @EnableRedisHttpSession. The following example shows how to customize Spring Session’s cookie:spring-doc.cn

	@Bean
	public CookieSerializer cookieSerializer() {
		DefaultCookieSerializer serializer = new DefaultCookieSerializer();
		serializer.setCookieName("JSESSIONID"); (1)
		serializer.setCookiePath("/"); (2)
		serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$"); (3)
		return serializer;
	}
1 We customize the name of the cookie to be JSESSIONID.
2 We customize the path of the cookie to be / (rather than the default of the context root).
3 We customize the domain name pattern (a regular expression) to be ^.?\\.(\\w\\.[a-z]+)$. This allows sharing a session across domains and applications. If the regular expression does not match, no domain is set and the existing domain is used. If the regular expression matches, the first grouping is used as the domain. This means that a request to child.example.com sets the domain to example.com. However, a request to localhost:8080/ or 192.168.1.100:8080/ leaves the cookie unset and, thus, still works in development without any changes being necessary for production.
You should only match on valid domain characters, since the domain name is reflected in the response. Doing so prevents a malicious user from performing such attacks as HTTP Response Splitting.

The following configuration options are available:spring-doc.cn

  • cookieName: The name of the cookie to use. Default: SESSION.spring-doc.cn

  • useSecureCookie: Specifies whether a secure cookie should be used. Default: Use the value of HttpServletRequest.isSecure() at the time of creation.spring-doc.cn

  • cookiePath: The path of the cookie. Default: The context root.spring-doc.cn

  • cookieMaxAge: Specifies the max age of the cookie to be set at the time the session is created. Default: -1, which indicates the cookie should be removed when the browser is closed.spring-doc.cn

  • jvmRoute: Specifies a suffix to be appended to the session ID and included in the cookie. Used to identify which JVM to route to for session affinity. With some implementations (that is, Redis) this option provides no performance benefit. However, it can help with tracing logs of a particular user.spring-doc.cn

  • domainName: Allows specifying a specific domain name to be used for the cookie. This option is simple to understand but often requires a different configuration between development and production environments. See domainNamePattern as an alternative.spring-doc.cn

  • domainNamePattern: A case-insensitive pattern used to extract the domain name from the HttpServletRequest#getServerName(). The pattern should provide a single grouping that is used to extract the value of the cookie domain. If the regular expression does not match, no domain is set and the existing domain is used. If the regular expression matches, the first grouping is used as the domain.spring-doc.cn

  • sameSite: The value for the SameSite cookie directive. To disable the serialization of the SameSite cookie directive, you may set this value to null. Default: Laxspring-doc.cn

  • rememberMeRequestAttribute: The request attribute name that indicates remember-me login. If specified, the cookie will be written as Integer.MAX_VALUE.spring-doc.cn

If you are using SpringSessionRememberMeServices and you are declaring a custom DefaultCookieSerializer bean, you should set the rememberMeRequestAttribute field to ensure that Spring Session relies on session expiration rather than cookie expiration. To do so, you can use the following code snippet: defaultCookieSerializer.setRememberMeRequestAttribute(SpringSessionRememberMeServices.REMEMBER_ME_LOGIN_ATTR);spring-doc.cn

You can customize how the session cookie is written in a WebFlux application by exposing a WebSessionIdResolver as a Spring bean. Spring Session uses a CookieWebSessionIdResolver by default. The following example shows how to customize Spring Session’s cookie:spring-doc.cn

	@Bean
	public WebSessionIdResolver webSessionIdResolver() {
		CookieWebSessionIdResolver resolver = new CookieWebSessionIdResolver();
		resolver.setCookieName("JSESSIONID"); (1)
		resolver.addCookieInitializer((builder) -> builder.path("/")); (2)
		resolver.addCookieInitializer((builder) -> builder.sameSite("Strict")); (3)
		return resolver;
	}
1 We customize the name of the cookie to be JSESSIONID.
2 We customize the path of the cookie to be / (rather than the default of the context root).
3 We customize the SameSite cookie directive to be Strict.

Providing a Spring Session implementation of ReactiveSessionRegistry

Spring Session provides integration with Spring Security to support its reactive concurrent session control. This allows limiting the number of active sessions that a single user can have concurrently, but, unlike the default Spring Security support, this also works in a clustered environment. This is done by providing the SpringSessionBackedReactiveSessionRegistry implementation of Spring Security’s ReactiveSessionRegistry interface.spring-doc.cn

Defining SpringSessionBackedReactiveSessionRegistry as a bean
@Bean
public <S extends Session> SpringSessionBackedReactiveSessionRegistry<S> sessionRegistry(
        ReactiveSessionRepository<S> sessionRepository,
        ReactiveFindByIndexNameSessionRepository<S> indexedSessionRepository) {
    return new SpringSessionBackedReactiveSessionRegistry<>(sessionRepository, indexedSessionRepository);
}

Please, refer to Spring Security Concurrent Sessions Control documentation for more ways of using the ReactiveSessionRegistry. You can also check a sample application here.spring-doc.cn