Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookie domain and path with Spring boot

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?

like image 866
zhe zhu Avatar asked Jan 22 '16 07:01

zhe zhu


People also ask

How do I set spring boot cookies?

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.

Can you set domain in cookie?

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.

How do I set cookies to all path?

In your Java server, you should call cookie. setPath("/") before adding it to response. Such cookie will match all request URIs.


2 Answers

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=/
like image 200
sthzg Avatar answered Oct 19 '22 01:10

sthzg


(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;
}
like image 2
EwyynTomato Avatar answered Oct 19 '22 02:10

EwyynTomato