Add secure flag to JSESSIONID cookie in spring automatically

ST-DDT :

I have a tomcat application server that is behind a nginx. SSL terminates on the nginx. The Spring web-mvc application that is deployed on the tomcat should set the secure flag on the JSESSIONID. It would be cool if spring has some automatic detection for this so I don't get bothered during development because I don't have SSL there.

Is there a way to tell spring to set the flag automatically?

I use JavaConfig to setup the application and use Maven to create a deployable war-file.

I have checked this already, but this looks somehow ugly and static: set 'secure' flag to JSESSION id cookie

Stefan Isele - prefabware.com :

When you use spring-session, e.g. to persist your session in reddis, this is indeed done automatically. The cookie is than created by org.springframework.session.web.http.CookieHttpSessionStrategy which in CookieHttpSessionStrategy#createSessionCookie checks if the request comes via HTTPS and sets secure accordingly:

sessionCookie.setSecure(request.isSecure());

If you do not use spring-session, you can configure secure cookies using a ServletContextInitializer. Use a application property, to set it to true/false depending on a 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 profile 'prod' is not active):

secure.cookie=false

application-prod.properties (only used when profile 'prod' is active, overwrites value in application.properties):

secure.cookie=false

start your application on the prod server with :

--spring.profiles.active=prod

Sounds like some effort, if you have not worked with profiles so far, but you will most likely need a profile for prod environment anyway, so its really worth it.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452927&siteId=1