1

I'm trying to add the secure flag to the session cookie in a Java web application. The standard approach however presents a problem, in that when secure is true, even http requests will get the secure flag. This means that the web server does not pick up on the cookie on subsiquent requests and we end up with a new session. It works fine on HTTPS. The application in question has multiple entry points, from different domains and some internal entry points as well with an internal IP. Some are HTTPS, some are HTTP. I need to be able to get the secure flag to be set for HTTPS requests, but HTTP ones. This needs to be done by domain though, rather than by protocol because, all the HTTPS requests go through a load balancer that does SSL offloading, so by the request arrives at the web server (which is jboss 7.1.1) it is HTTP, even though the client would see it as HTTPS and would need the secure flag in the session cookie. Here is the config I tried:

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

I have had to set secure to false however, as otherwise none of the HTTP entry points work.

Martin Cassidy
  • 686
  • 1
  • 9
  • 28

1 Answers1

0

This can be acheived with a custom valve, that provides a hook into the creation of the request object. The secure flag is set in a cookie automatically (without the web.xml setting) if the servlet request is secure. Setting the secure flag in the request can be done from the valve.

The load balancer adds on the header Front-End-Https which the valve detects and sets secure accordingly.

Here is the valve class:

import java.io.IOException;

import javax.servlet.ServletException;

import org.apache.catalina.Valve;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;

public class SecureRequestModifyingValve extends ValveBase
{
    private static final String LB_HTTPS_HEADER = "Front-End-Https";

    @Override
    public void invoke(final Request request, final Response response) throws IOException, ServletException
    {
        final String httpsHeader = request.getHeader(LB_HTTPS_HEADER);
        request.setSecure(httpsHeader != null && httpsHeader.equalsIgnoreCase("on"));
        getNext().invoke(request, response);
    }
}

I have got jboss to use it by adding the following to jboss-web.xml within the WAR.

<valve>
    <class-name>com.lifecycle.framework.valve.SecureRequestModifyingValve
    </class-name>
</valve>

I imagine other containers let you do something similar as well.

Martin Cassidy
  • 686
  • 1
  • 9
  • 28