I need to set httpOnly and secure flags on session cookie in Google App Engine.
I tried the following in web.xml
:
<session-config>
<cookie-config>
<http-only>true</http-only>
</cookie-config>
</session-config>
However, this didn't work.
I also tried this in the top of every JSP:
String sessionid = request.getSession().getId();
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");
How can I achieve this?
I had the same problem with Google App Engine, but I wanted to add Secure
attribute to all cookies. The following shows how I've added Secure
attribute to all cookies. I'm almost sure that this solution will work for you just by substituting Secure
with HttpOnly
.
I've implemented a security filter and made a mapping to the pages that I want the Secure
attribute be set.
<filter>
<filter-name>Security Filter</filter-name>
<filter-class>common.SecurityFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Security Filter</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>
My first try was to wrap the response into my custom HttpServletResponseWrapper
. All was fine except the session cookie doesn't get the attribute. I debugged around and found that the session cookie is not added using the mechanism I've expected. I've then noticed that after you touch the session the session cookie is magically added to the response headers e.g. the headers now consists the line Set-Cookie: JSESSIONID=abcdef;Path=/
but the cookie wasn't added using the wrapper object that I've created. I've figured out that after I've touched the session I can set the cookie that I want with the attributes that I want. So the workaround was easy.
public class SecurityFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// wrap the response
response = new SecureCookieSetter((HttpServletResponse)response);
// touch the session
(HttpServletRequest)request.getSession();
// overwriting the cookie with Secure attribute set
((HttpServletResponse)response).setHeader("Set-Cookie", "JSESSIONID=" + ((HttpServletRequest)request).getSession().getId() + ";Path=/");
}
}
public class SecureCookieSetter extends HttpServletResponseWrapper {
public SecureCookieSetter(HttpServletResponse response) {
super(response);
}
@Override
public void addCookie(Cookie cookie) {
cookie.setSecure(true);
super.addCookie(cookie);
}
@Override
public void addHeader(String name, String value) {
if ((name.equals("Set-Cookie")) && (!value.matches("(^|.*;)\\s*Secure"))) {
value = value + ";Secure";
}
super.addHeader(name, value);
}
@Override
public void setHeader(String name, String value) {
if ((name.equals("Set-Cookie")) && (!value.matches("(^|.*;)\\s*Secure"))) {
value = value + ";Secure";
}
super.setHeader(name, value);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With