I created a quick-and-dirty spring-boot app and here's what I came up with.
The ServletInitializer that is generated, you can alter it in this fashion:
package com.division6.bootr;
import java.util.Collections;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// This can be done here or as the last step in the method
// Doing it in this order will initialize the Spring
// Framework first, doing it as last step will initialize
// the Spring Framework after the Servlet configuration is
// established
super.onStartup(servletContext);
// This will set to use COOKIE only
servletContext
.setSessionTrackingModes(
Collections.singleton(SessionTrackingMode.COOKIE)
);
// This will prevent any JS on the page from accessing the
// cookie - it will only be used/accessed by the HTTP transport
// mechanism in use
SessionCookieConfig sessionCookieConfig=
servletContext.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(true);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBootrApplication.class);
}
}
AUTHOR NOTE
I am not 100% sure when this was introduced but by introducing the following parameters, the same can be accomplished without having to write code:
- server.servlet.session.cookie.http-only=true
- server.servlet.session.tracking-modes=cookie