<p>After reading Jeff's blog post on <a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">Protecting Your Cookies: HttpOnly</a>. I'd like to implement HttpOnly cookies in my web application.</p>

<p>How do you tell tomcat to use http only cookies for sessions?</p>

[{'answer_id': 33456, 'author': 'Shabaz', 'author_id': 1827, 'author_profile': 'https://Stackoverflow.com/users/1827', 'pm_score': 3, 'selected': False, 'text': '<p>For session cookies it doesn\'t seem to be supported in Tomcat yet. See the bug report <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=44382" rel="noreferrer">Need to add support for HTTPOnly session cookie parameter</a>. A somewhat involved work-around for now can be found <a href="http://manicode.blogspot.com/2008/03/httponly-support-for-apache-tomcat.html" rel="noreferrer">here</a>, 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. </p>\n\n<p>To summarize the work-around, it involves downloading the 5.5 <a href="http://tomcat.apache.org/tomcat-5.5-doc/building.html" rel="noreferrer">source</a>, and then change the source in the following places:</p>\n\n<p><em>org.apache.catalina.connector.Request.java</em></p>\n\n<pre><code>//this is what needs to be changed\n//response.addCookieInternal(cookie);\n\n//this is whats new\nresponse.addCookieInternal(cookie, true);\n}\n</code></pre>\n\n<p><em>org.apache.catalina.connectorResponse.addCookieInternal</em></p>\n\n<pre><code>public void addCookieInternal(final Cookie cookie) {\naddCookieInternal(cookie, false);\n}\n\npublic void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {\n\nif (isCommitted())\nreturn;\n\nfinal StringBuffer sb = new StringBuffer();\n//web application code can receive a IllegalArgumentException\n//from the appendCookieValue invokation\nif (SecurityUtil.isPackageProtectionEnabled()) {\nAccessController.doPrivileged(new PrivilegedAction() {\npublic Object run(){\nServerCookie.appendCookieValue\n(sb, cookie.getVersion(), cookie.getName(),\ncookie.getValue(), cookie.getPath(),\ncookie.getDomain(), cookie.getComment(),\ncookie.getMaxAge(), cookie.getSecure());\nreturn null;\n}\n});\n} else {\nServerCookie.appendCookieValue\n(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),\ncookie.getPath(), cookie.getDomain(), cookie.getComment(),\ncookie.getMaxAge(), cookie.getSecure());\n}\n//of course, we really need to modify ServerCookie\n//but this is the general idea\nif (HTTPOnly) {\nsb.append("; HttpOnly");\n}\n\n//if we reached here, no exception, cookie is valid\n// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )\n// RFC2965 is not supported by browsers and the Servlet spec\n// asks for 2109.\naddHeader("Set-Cookie", sb.toString());\n\ncookies.add(cookie);\n}\n</code></pre>\n'}, {'answer_id': 33461, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 4, 'selected': False, 'text': '<blockquote>\n  <p><strong>Update: The JSESSIONID stuff here is\n  only for older containers. Please use\n  jt\'s currently accepted answer unless\n  you are using &lt; Tomcat 6.0.19 or &lt; Tomcat\n  5.5.28 or another container that does not support HttpOnly JSESSIONID cookies as a config option.</strong></p>\n</blockquote>\n\n<p>When setting cookies in your app, use</p>\n\n<pre><code>response.setHeader( "Set-Cookie", "name=value; HttpOnly");\n</code></pre>\n\n<p>However, in many webapps, the most important cookie is the session identifier, which is automatically set by the container as the JSESSIONID cookie.</p>\n\n<p>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 <strike><a href="http://keepitlocked.net/archive/2007/11/05/java-and-httponly.aspx" rel="noreferrer">http://keepitlocked.net/archive/2007/11/05/java-and-httponly.aspx</a></strike> <a href="http://alexsmolen.com/blog/?p=16" rel="noreferrer">http://alexsmolen.com/blog/?p=16</a> suggests adding the following in a filter.</p>\n\n<pre><code>if (response.containsHeader( "SET-COOKIE" )) {\n  String sessionid = request.getSession().getId();\n  response.setHeader( "SET-COOKIE", "JSESSIONID=" + sessionid \n                      + ";Path=/&lt;whatever&gt;; Secure; HttpOnly" );\n} \n</code></pre>\n\n<p>but note that this will overwrite all cookies and only set what you state here in this filter. </p>\n\n<p>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. </p>\n\n<p>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.</p>\n\n<p>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.</p>\n'}, {'answer_id': 1088009, 'author': 'jt.', 'author_id': 4362, 'author_profile': 'https://Stackoverflow.com/users/4362', 'pm_score': 7, 'selected': True, 'text': '<p>httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.</p>\n\n<p>See the <a href="http://tomcat.apache.org/tomcat-6.0-doc/changelog.html" rel="noreferrer">changelog</a> entry for bug 44382. </p>\n\n<p>The last comment for bug <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=44382" rel="noreferrer">44382</a> 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.</p>\n\n<p>The httpOnly functionality can be enabled for all webapps in <strong>conf/context.xml</strong>:</p>\n\n<pre><code>&lt;Context useHttpOnly="true"&gt;\n...\n&lt;/Context&gt;\n</code></pre>\n\n<p>My interpretation is that it also works for an individual context by setting it on the desired <strong><em>Context</em></strong> entry in <strong>conf/server.xml</strong> (in the same manner as above).</p>\n'}, {'answer_id': 1465092, 'author': 'Hendrik Brummermann', 'author_id': 177701, 'author_profile': 'https://Stackoverflow.com/users/177701', 'pm_score': 4, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {\n    if (response.containsHeader("SET-COOKIE")) {\n        String sessionid = request.getSession().getId();\n        String contextPath = request.getContextPath();\n        String secure = "";\n        if (request.isSecure()) {\n            secure = "; Secure"; \n        }\n        response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid\n                         + "; Path=" + contextPath + "; HttpOnly" + secure);\n    }\n}\n</code></pre>\n'}, {'answer_id': 3516432, 'author': 'Pete Brumm', 'author_id': 335770, 'author_profile': 'https://Stackoverflow.com/users/335770', 'pm_score': 2, 'selected': False, 'text': '<p>also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.</p>\n\n<p>the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.</p>\n'}, {'answer_id': 14610452, 'author': 'Jesse Vogt', 'author_id': 9822, 'author_profile': 'https://Stackoverflow.com/users/9822', 'pm_score': 2, 'selected': False, 'text': '<p>For cookies that I am explicitly setting, I switched to use <a href="http://shiro.apache.org/static/current/apidocs/org/apache/shiro/web/servlet/SimpleCookie.html" rel="nofollow">SimpleCookie</a> provided by <a href="http://shiro.apache.org/" rel="nofollow">Apache Shiro</a>. 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.</p>\n\n<p>For setting a cookie on a response, rather than doing <code>response.addCookie(cookie)</code> you need to do <code>cookie.saveTo(request, response)</code>.</p>\n'}, {'answer_id': 30995999, 'author': 'Alireza Fattahi', 'author_id': 2648077, 'author_profile': 'https://Stackoverflow.com/users/2648077', 'pm_score': 4, 'selected': False, 'text': '<p>If your web server supports Serlvet 3.0 spec, like tomcat 7.0+, you can use below in <code>web.xml</code> as:</p>\n\n<pre><code>&lt;session-config&gt;\n  &lt;cookie-config&gt;\n     &lt;http-only&gt;true&lt;/http-only&gt;        \n     &lt;secure&gt;true&lt;/secure&gt;        \n  &lt;/cookie-config&gt;\n&lt;/session-config&gt;\n</code></pre>\n\n<p>As mentioned in docs:</p>\n\n<blockquote>\n  <p><strong>HttpOnly</strong>: Specifies whether any session tracking cookies created by\n  this web application will be marked as HttpOnly </p>\n  \n  <p><strong>Secure</strong>: Specifies\n  whether any session tracking cookies created by this web application\n  will be marked as secure even if   the request that initiated the\n  corresponding session is using plain HTTP instead of HTTPS</p>\n</blockquote>\n\n<p>Please refer to <a href="https://stackoverflow.com/questions/15510354/how-to-set-httponly-and-session-cookie-for-java-web-appliaction">how to set httponly and session cookie for java web application</a></p>\n'}, {'answer_id': 34147407, 'author': 'Systemsplanet', 'author_id': 586841, 'author_profile': 'https://Stackoverflow.com/users/586841', 'pm_score': 1, 'selected': False, 'text': '<p>In Tomcat6, You can conditionally enable from your HTTP Listener Class:</p>\n\n<pre><code>public void contextInitialized(ServletContextEvent event) {                 \n   if (Boolean.getBoolean("HTTP_ONLY_SESSION")) HttpOnlyConfig.enable(event);\n}\n</code></pre>\n\n<p>Using this class</p>\n\n<pre><code>import java.lang.reflect.Field;\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletContextEvent;\nimport org.apache.catalina.core.StandardContext;\npublic class HttpOnlyConfig\n{\n    public static void enable(ServletContextEvent event)\n    {\n        ServletContext servletContext = event.getServletContext();\n        Field f;\n        try\n        { // WARNING TOMCAT6 SPECIFIC!!\n            f = servletContext.getClass().getDeclaredField("context");\n            f.setAccessible(true);\n            org.apache.catalina.core.ApplicationContext ac = (org.apache.catalina.core.ApplicationContext) f.get(servletContext);\n            f = ac.getClass().getDeclaredField("context");\n            f.setAccessible(true);\n            org.apache.catalina.core.StandardContext sc = (StandardContext) f.get(ac);\n            sc.setUseHttpOnly(true);\n        }\n        catch (Exception e)\n        {\n            System.err.print("HttpOnlyConfig cant enable");\n            e.printStackTrace();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 53652036, 'author': 'Ravipati Praveen', 'author_id': 3876619, 'author_profile': 'https://Stackoverflow.com/users/3876619', 'pm_score': 2, 'selected': False, 'text': '<p>I Found in <a href="https://www.owasp.org/index.php/HttpOnly" rel="nofollow noreferrer">OWASP</a></p>\n\n<pre><code>&lt;session-config&gt;\n  &lt;cookie-config&gt;\n    &lt;http-only&gt;true&lt;/http-only&gt;\n  &lt;/cookie-config&gt;\n&lt;/session-config&gt;\n</code></pre>\n\n<p>this is also fix for "httponlycookies in config" security issue</p>\n'}, {'answer_id': 67748208, 'author': 'Akash Chatterjee', 'author_id': 5010765, 'author_profile': 'https://Stackoverflow.com/users/5010765', 'pm_score': 0, 'selected': False, 'text': '<p>Implementation: in Tomcat 7.x/8.x/9.x</p>\n<p>Go to Tomcat &gt;&gt; conf folder\nOpen web.xml and add below in session-config section</p>\n<pre><code>    &lt;cookie-config&gt;\n        &lt;http-only&gt;true&lt;/http-only&gt;\n        &lt;secure&gt;true&lt;/secure&gt;\n    &lt;/cookie-config&gt;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/33412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1310/']