13

In Tomcat, we can do it like this:

<Context useHttpOnly="true" sessionCookiePath="/"sessionCookieDomain=".XXXX.com"/>

I want to share the cookie for second level domain with Spring Boot, how to do it?

Oliv
  • 10,221
  • 3
  • 55
  • 76
zhe zhu
  • 131
  • 1
  • 1
  • 3

3 Answers3

20

Settings for the server that Spring Boot embeds are available as application properties (listed here under the section # EMBEDDED SERVER CONFIGURATION and the namespace server.servlet.session.cookie.*).

The equivalent to the Tomcat config from above should be:

# properties in /src/resources/application.properties
server.servlet.session.cookie.domain=.XXXX.com
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.path=/
Matt Busche
  • 14,216
  • 5
  • 36
  • 61
sthzg
  • 5,514
  • 2
  • 29
  • 50
  • 1
    forgot to add `servlet` between server and session – OzzyTheGiant Jul 02 '18 at 20:23
  • Ozzy's right. It should be server.servlet.session.cookie.domain according to the documentation (https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html) – Samuel Aug 02 '18 at 16:18
  • I had to implement following for spring boot 2+ to make it work - https://stackoverflow.com/a/39196298/716027 – fedor.belov Dec 15 '18 at 16:53
2

(This applies to Spring 1.5.x at the time of this writing)

To add to @radrocket81's reply, here's an example code. Also this is how you set the max-age and other properties of Spring boot cookies if you enabled Redis session by @EnableRedisHttpSession as application property server.session won't be applied.

@Bean
public <S extends ExpiringSession> SessionRepositoryFilter<? extends ExpiringSession> springSessionRepositoryFilter(SessionRepository<S> sessionRepository, ServletContext servletContext) {
    SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<S>(sessionRepository);
    sessionRepositoryFilter.setServletContext(servletContext);
    CookieHttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy();
    httpSessionStrategy.setCookieSerializer(this.cookieSerializer());
    sessionRepositoryFilter.setHttpSessionStrategy(httpSessionStrategy);
    return sessionRepositoryFilter;
}

private CookieSerializer cookieSerializer() {
    DefaultCookieSerializer serializer = new DefaultCookieSerializer();
    serializer.setCookieName("CUSTOM_SESSION_KEY");
    serializer.setDomainName("domain.com");
    serializer.setCookiePath("/");
    serializer.setCookieMaxAge(10); //Set the cookie max age in seconds, e.g. 10 seconds
    return serializer;
}
EwyynTomato
  • 4,009
  • 1
  • 31
  • 39
0

My solution was to define a CookieSerializer bean and provide the domain pattern that fits my setup.

Like this: Spring Session - Custom Cookie

radrocket81
  • 299
  • 3
  • 10