8

I need to restrict access to a cookie containing a session token so that javascript can't access it. Advice that was given was to set Secure and HttpOnly flags on the cookie.

I was having trouble with cookies not being set when using @ResponseBody, so I'm setting the cookies inside a HandlerInterceptor.

public class COOKIEFilter implements org.springframework.web.servlet.HandlerInterceptor  {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        Cookie cookie = new Cookie("timestamp", new Long(new Date().getTime()).toString());
        cookie.setSecure(true);
        // how do I set the http-only flag?
        httpServletResponse.addCookie(cookie);

        return true;
    }

As shown in the chrome console, Secure is set, but not HTTP

Showing that secure flag is being set

I've tried adding parameters to web.xml under servlet 3.0 sepcification that allows for secure and http-only to be set on session cookies, but since I need to handle the session myself (Spring MVC application needs to remain stateless), that won't work for me.

Update:

I'm using Tomcat7, currently with Servlet 2.5 and Spring 3.2.8.

Jan Vladimir Mostert
  • 12,380
  • 15
  • 80
  • 137

3 Answers3

10

It can be set as cookie.setHttpOnly(true) just like you did for secure.

wolfram77
  • 2,841
  • 3
  • 23
  • 33
1

You need to set the HttpOnly as below:

Cookie cookie = new Cookie("timestamp", new Long(new Date().getTime()).toString() + ";HttpOnly");

It needs to follow cookieName=cookieValue;HttpOnly;Secure format

Mithun
  • 7,747
  • 6
  • 52
  • 68
-2

Replace:

 Cookie cookie = new Cookie("timestamp", new Long(new Date().getTime()).toString());

with the following

Cookie cookie = new Cookie("timestamp", new Long(new Date().getTime()).toString()+";HttpOnly");

This might work.

iaforek
  • 2,860
  • 5
  • 40
  • 56
sathya_dev
  • 513
  • 3
  • 15