在 Spring MVC 控制器中创建的 cookie 上设置 http-only

Set http-only on cookies created in Spring MVC Controller

我需要限制对包含会话令牌的 cookie 的访问,以便 javascript 无法访问它。 给出的建议是在 cookie 上设置 Secure 和 HttpOnly 标志。

我遇到了使用@ResponseBody 时未设置 cookie 的问题,因此我在 HandlerInterceptor 中设置了 cookie。

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;
    }

如 chrome 控制台所示,已设置安全,但未设置 HTTP

我尝试在 servlet 3.0 规范下向 web.xml 添加参数,允许在会话 cookie 上设置安全和仅 http,但由于我需要自己处理会话(Spring MVC 应用程序需要保持无状态),这对我不起作用。

更新:

我正在使用 Tomcat7,目前使用 Servlet 2.5 和 Spring 3.2.8。

它可以设置为 cookie.setHttpOnly(true) 就像你为安全所做的那样。

替换:

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

与以下

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

这可能有效。

您需要设置 HttpOnly 如下:

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

需要遵循cookieName=cookieValue;HttpOnly;Secure格式