Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flag session cookie as secure (https only) in tomcat 6

I have done a lot of googeling and could not find an answer. I have tried setting the following in the web.xml file in the war with no impact :

<session-config>
        <session-timeout>60</session-timeout>
        <cookie-config>
            <http-only>true</http-only>
            <secure>true</secure>
        </cookie-config>
    </session-config>

Adding useHttpOnly in the tomcat context.xml file works to restrict cookies to http only but I still need to make them secure.

like image 595
Assaf Karmon Avatar asked Oct 08 '22 01:10

Assaf Karmon


1 Answers

You don't have to do anything. As long as the request that starts the session is https Tomcat will mark the session cookie as secure.

I also looked to see if there was anything that officially documented that fact but I couldn't find it. But that is the behavior of at least Tomcat 6.0.32 and up.

Here is the code from org/apache/catalina/connector/Request.java which, at the end of the method, checks to see if the request is secure and if it is, sets the secure flag on the cookie:

/**
 * Configures the given JSESSIONID cookie.
 *
 * @param cookie The JSESSIONID cookie to be configured
 */
protected void configureSessionCookie(Cookie cookie) {
    cookie.setMaxAge(-1);

    Context ctxt = getContext();

    String contextPath = null;
    if (ctxt != null && !getConnector().getEmptySessionPath()) {
        if (ctxt.getSessionCookiePath() != null) {
            contextPath = ctxt.getSessionCookiePath();
        } else {
            contextPath = ctxt.getEncodedPath();
        }
    }
    if ((contextPath != null) && (contextPath.length() > 0)) {
        cookie.setPath(contextPath);
    } else {
        cookie.setPath("/");
    }

    if (ctxt != null && ctxt.getSessionCookieDomain() != null) {
        cookie.setDomain(ctxt.getSessionCookieDomain());
    }

    if (isSecure()) {
        cookie.setSecure(true);
    }
}

UPDATE: you can manually try to set this by yourself by using a filter etc.. you can check an example from set 'secure' flag to JSESSION id cookie

like image 105
sourcedelica Avatar answered Oct 13 '22 11:10

sourcedelica