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?
In a Spring Boot application, a cookie can be set by using the Cookie class and add in server response using HttpServletResponse class, similarly, a cookie can be retrieved by using @CookieValue annotation.
Set a cookie domain The domain can be used to specify a subdomain for your cookie. If not set, it defaults to the host portion even if using a subdomain (if on subdomain.mydomain.com, by default it's set to mydomain.com). Domain cookies are included in subdomains.
In your Java server, you should call cookie. setPath("/") before adding it to response. Such cookie will match all request URIs.
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=/
(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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With