Add safe flag to JSESSIONID cookie in spring automatically

I have a tomcat application server which is located behind nginx. SSL terminates on nginx. Spring web-mvc application deployed on tomcat should set the secure flag to JSESSIONID. It would be great if Spring has some automatic discovery for this, so I don't worry 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 configure the application and use Maven to create a deployed war file.

I already checked this, but it looks somehow ugly and static: set 'secure' in JSESSION id cookie

+7
source share
4 answers

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-, .

+10

Spring Boot, . application.properties:

server.servlet.session.cookie.secure=true

: Spring docs - A.

HTTPS, - , false HTTPS. cookie .

+2

in your application.yml just add

server:
  session:
    cookie:
      secure: true
0
source

Add another option

You can use ServletContextInitializer to set a secure cookie and only http flag

@Bean
public ServletContextInitializer servletContextInitializer() {
    return new ServletContextInitializer() {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
            SessionCookieConfig sessionCookieConfig = servletContext.getSessionCookieConfig();
            sessionCookieConfig.setHttpOnly(true);
            sessionCookieConfig.setSecure(true);
        }
    };
}
0
source

Source: https://habr.com/ru/post/1653179/


All Articles