How do you configure HttpOnly cookies in tomcat / java webapps?
Asked Answered
D

11

77

After reading Jeff's blog post on Protecting Your Cookies: HttpOnly. I'd like to implement HttpOnly cookies in my web application.

How do you tell tomcat to use http only cookies for sessions?

Dryad answered 28/8, 2008 at 21:9 Comment(0)
F
66

httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.

See the changelog entry for bug 44382.

The last comment for bug 44382 states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released.

The httpOnly functionality can be enabled for all webapps in conf/context.xml:

<Context useHttpOnly="true">
...
</Context>

My interpretation is that it also works for an individual context by setting it on the desired Context entry in conf/server.xml (in the same manner as above).

Flavorful answered 6/7, 2009 at 16:46 Comment(2)
I'm running Tomcat 5.5.36. This useHttpOnly attribute seems to work only for JSESSIONID cookie. I added this flag on all my contexts to make sure all cookies would be added the "; HttpOnly" at the end. However, only JSESSIONID was affected as follows: Set-Cookie= JSESSIONID=25E8F...; Path=/custompath; HttpOnly mycustomcookie1=xxxxxxx; Path=/ mycustomcookie2=1351101062602; Path=/ mycustomcookie3=0; Path=/ mycustomcookie4=1; Path=/; Secure mycustomcookie5=4000; Expires=Sat, 22-Oct-2022 17:51:02 GMT; Path=/ Is anything else I'm doing wrong?Biddick
This documentation seems to indicate that the useHttpOnly flag only pertains to the session id cookie: tomcat.apache.org/tomcat-5.5-doc/config/… I think this was a stop-gap measure intended to protect the session cookie. The ability to flag cookies as HttpOnly wasn't part of the Servlet spec until 3.0 (covered by Tomcat 7): today.java.net/pub/a/today/2008/10/14/…Flavorful
G
20

Update: The JSESSIONID stuff here is only for older containers. Please use jt's currently accepted answer unless you are using < Tomcat 6.0.19 or < Tomcat 5.5.28 or another container that does not support HttpOnly JSESSIONID cookies as a config option.

When setting cookies in your app, use

response.setHeader( "Set-Cookie", "name=value; HttpOnly");

However, in many webapps, the most important cookie is the session identifier, which is automatically set by the container as the JSESSIONID cookie.

If you only use this cookie, you can write a ServletFilter to re-set the cookies on the way out, forcing JSESSIONID to HttpOnly. The page at http://keepitlocked.net/archive/2007/11/05/java-and-httponly.aspx http://alexsmolen.com/blog/?p=16 suggests adding the following in a filter.

if (response.containsHeader( "SET-COOKIE" )) {
  String sessionid = request.getSession().getId();
  response.setHeader( "SET-COOKIE", "JSESSIONID=" + sessionid 
                      + ";Path=/<whatever>; Secure; HttpOnly" );
} 

but note that this will overwrite all cookies and only set what you state here in this filter.

If you use additional cookies to the JSESSIONID cookie, then you'll need to extend this code to set all the cookies in the filter. This is not a great solution in the case of multiple-cookies, but is a perhaps an acceptable quick-fix for the JSESSIONID-only setup.

Please note that as your code evolves over time, there's a nasty hidden bug waiting for you when you forget about this filter and try and set another cookie somewhere else in your code. Of course, it won't get set.

This really is a hack though. If you do use Tomcat and can compile it, then take a look at Shabaz's excellent suggestion to patch HttpOnly support into Tomcat.

Gwendagwendolen answered 28/8, 2008 at 21:37 Comment(4)
This code removes the ;Secure flag thus rendering the usage of https pointless.Zeiger
In Servlet 3.0 complaint application servers I can set the HttpOnly and secure flags for the session cookie (JSESSIONID) by adding the following to the web.xml: <session-config> <cookie-config> <secure>true</secure> <http-only>true</http-only> </cookie-config> </session-config>Typehigh
@RogerJin please post this as a new answer, this 6-year old answer is getting increasingly out-of-date.Gwendagwendolen
Be careful with setHeader because it deletes all the previous headers with the same name. For example, it can delete the JSESSIONID cookie when you set a custom cookie. Instead use response.addHeader() for custom cookiesNotify
Z
15

Please be careful not to overwrite the ";secure" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.

private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
    if (response.containsHeader("SET-COOKIE")) {
        String sessionid = request.getSession().getId();
        String contextPath = request.getContextPath();
        String secure = "";
        if (request.isSecure()) {
            secure = "; Secure"; 
        }
        response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
                         + "; Path=" + contextPath + "; HttpOnly" + secure);
    }
}
Zeiger answered 23/9, 2009 at 10:4 Comment(1)
Note that using request.isSecure() is not always accurate. Consider a load-balanced node behind the LB that performs SSL acceleration. The request from the browser to the load balancer will come over HTTPS, while the request between load balancer and the actual server will come over plain HTTP. This will result in request.isSecure() being false, while the browser is using SSL.Demigod
U
14

If your web server supports Serlvet 3.0 spec, like tomcat 7.0+, you can use below in web.xml as:

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

As mentioned in docs:

HttpOnly: Specifies whether any session tracking cookies created by this web application will be marked as HttpOnly

Secure: Specifies whether any session tracking cookies created by this web application will be marked as secure even if the request that initiated the corresponding session is using plain HTTP instead of HTTPS

Please refer to how to set httponly and session cookie for java web application

Urissa answered 23/6, 2015 at 7:4 Comment(0)
P
10

For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report Need to add support for HTTPOnly session cookie parameter. A somewhat involved work-around for now can be found here, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.

To summarize the work-around, it involves downloading the 5.5 source, and then change the source in the following places:

org.apache.catalina.connector.Request.java

//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}

org.apache.catalina.connectorResponse.addCookieInternal

public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}
Perennate answered 28/8, 2008 at 21:36 Comment(0)
O
2

also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.

the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.

Outherod answered 18/8, 2010 at 20:33 Comment(0)
C
2

For cookies that I am explicitly setting, I switched to use SimpleCookie provided by Apache Shiro. It does not inherit from javax.servlet.http.Cookie so it takes a bit more juggling to get everything to work correctly however it does provide a property set HttpOnly and it works with Servlet 2.5.

For setting a cookie on a response, rather than doing response.addCookie(cookie) you need to do cookie.saveTo(request, response).

Cardoon answered 30/1, 2013 at 17:49 Comment(0)
T
2

I Found in OWASP

<session-config>
  <cookie-config>
    <http-only>true</http-only>
  </cookie-config>
</session-config>

this is also fix for "httponlycookies in config" security issue

Trustless answered 6/12, 2018 at 13:0 Comment(0)
B
1

In Tomcat6, You can conditionally enable from your HTTP Listener Class:

public void contextInitialized(ServletContextEvent event) {                 
   if (Boolean.getBoolean("HTTP_ONLY_SESSION")) HttpOnlyConfig.enable(event);
}

Using this class

import java.lang.reflect.Field;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.catalina.core.StandardContext;
public class HttpOnlyConfig
{
    public static void enable(ServletContextEvent event)
    {
        ServletContext servletContext = event.getServletContext();
        Field f;
        try
        { // WARNING TOMCAT6 SPECIFIC!!
            f = servletContext.getClass().getDeclaredField("context");
            f.setAccessible(true);
            org.apache.catalina.core.ApplicationContext ac = (org.apache.catalina.core.ApplicationContext) f.get(servletContext);
            f = ac.getClass().getDeclaredField("context");
            f.setAccessible(true);
            org.apache.catalina.core.StandardContext sc = (StandardContext) f.get(ac);
            sc.setUseHttpOnly(true);
        }
        catch (Exception e)
        {
            System.err.print("HttpOnlyConfig cant enable");
            e.printStackTrace();
        }
    }
}
Bed answered 8/12, 2015 at 3:21 Comment(0)
R
0

Implementation: in Tomcat 7.x/8.x/9.x

Go to Tomcat >> conf folder Open web.xml and add below in session-config section

    <cookie-config>
        <http-only>true</http-only>
        <secure>true</secure>
    </cookie-config>
Reentry answered 29/5, 2021 at 5:54 Comment(0)
B
0

Since Java Enterprise Edition 6 (JEE 6),you can set cookie directly:

    cookie.setHttpOnly(true);
Blanket answered 10/5 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.