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

后端 未结 9 979
迷失自我
迷失自我 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:23

    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

    0 讨论(0)
  • 2020-11-27 11:25

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

    0 讨论(0)
  • 2020-11-27 11:27

    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.

    0 讨论(0)
提交回复
热议问题