When you use spring-session , for example. to continue the session in reddis, this is really done automatically. A cookie is created org.springframework.session.web.http.CookieHttpSessionStrategy, which CookieHttpSessionStrategy#createSessionCookiechecks to see if the request is received via HTTPS and accordingly sets protection:
sessionCookie.setSecure(request.isSecure());
If you are not using spring-session, you can set secure cookies with ServletContextInitializer. Use the application property to set it to true / false depending on the profile.
@Bean
public ServletContextInitializer servletContextInitializer(@Value("${secure.cookie}") boolean secure) {
return new ServletContextInitializer() {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.getSessionCookieConfig().setSecure(secure);
}
};
}
application.properties (used in dev when the prod profile is not active):
secure.cookie=false
application-prod.properties( prod), application.properties):
secure.cookie=false
prod
--spring.profiles.active=prod
- , , , , prod-, .