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

后端 未结 9 1005
迷失自我
迷失自我 2020-11-27 10:47

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 ht

9条回答
  •  时光取名叫无心
    2020-11-27 11:00

    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);
    }
    

提交回复
热议问题