Setting httponly in JSESSIONID cookie (Java EE 5)

99封情书 提交于 2019-12-30 02:10:14

问题


I'm trying to set the httponly flag on the JSESSIONID cookie. I'm working in Java EE 5, however, and can't use setHttpOnly(). First I tried to create my own JSESSIONID cookie from within the servlet's doPost() by using response.setHeader().

When that didn't work, I tried response.addHeader(). That didn't work either. Then, I learned that the servlet handled converting the session into a JSESSIONID cookie and inserting it into the http header so if I want to play with that cookie, I'll have to write a filter. I wrote a filter and played with setHeader()/addHeader() there, again to no avail.

Then, I learned that there's some flush/close action going on in the response object before it gets to the filter so if I want to manipulate the data, I need to extend HttpServletResponseWrapper and pass that to filterChain.doFilter(). This is done but I'm still not getting results. Clearly I'm doing something wrong but I don't know what.

I'm not sure if this is at all relevant to the question at hand but no html document is being returned by the servlet to the browser. All that's really happening is that some objects are being populated and returned to a JSP document. I've sort of assumed that The Session object is turned into a JSESSIONID cookie and wrapped -- along with the objects added to the request -- in an http header before being sent to the browser.

I'd be happy to post some code but I want to rule out the possibility that my difficulties stem from a misunderstanding of the theory first.


回答1:


Since the JSESSIONID cookie is managed by the servletcontainer, this setting is servletcontainer specific. It's unclear which one you're using, so here's an Apache Tomcat 6.0 targeted answer so that you know in which direction you'll have to look for your servletcontainer: you need to set the useHttpOnly attribute of the webapplication's <Context> element to true.

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

Also see this Tomcat documentation about the <Context> element.




回答2:


You can use this with Java EE 5:

For Java Enterprise Edition versions prior to Java EE 6 a common workaround is to overwrite the SET-COOKIE http response header with a session cookie value that explicitly appends the HttpOnly flag:

String sessionid = request.getSession().getId();
// be careful overwriting: JSESSIONID may have been set with other flags
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");

Source : https://www.owasp.org/index.php/HttpOnly

I test it into a filter



来源:https://stackoverflow.com/questions/2992473/setting-httponly-in-jsessionid-cookie-java-ee-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!