【问题标题】:Set http-only on cookies created in Spring MVC Controller在 Spring MVC 控制器中创建的 cookie 上设置 http-only
【发布时间】:2015-06-06 23:56:58
【问题描述】:

我需要限制对包含会话令牌的 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控制台所示,设置了Secure,但没有设置HTTP

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

更新:

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

【问题讨论】:

    标签: java spring spring-mvc cookies


    【解决方案1】:

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

    【讨论】:

    • 让我尝试将 servlet 规范提高到 3
    • 我没有使用过 Sping MVC 框架,但这适用于 Java servlet。您使用的Cookie 是来自javax.servlet.http.Cookie 吗?
    • 没错:javax.servlet.http.Cookie;从哪个 servlet 版本开始支持 setHttpOnly?
    • Java EE 6 Cookie
    • 上面写着Since: Servlet 3.0,让我来看看如何让 Spring 与 Servlet 3.0 配合得很好。
    【解决方案2】:

    替换:

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

    以下

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

    这可能有效。

    【讨论】:

    • 这只是将值设置为“1427955447675 Http-Only”
    • 是的,我错过了 ; .正如你所说的那样也行不通。我可以知道您使用的是哪个服务器。因为,某些服务器级别的配置可能会导致冲突
    【解决方案3】:

    你需要设置HttpOnly如下:

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

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

    【讨论】:

    • 我在 Chrome 控制台中看到的值现在是 "1427955789419,但没有设置 HTTP 标志。
    • 你的意思是说,经过上面的修改,你还是看不到HttpOnly
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2022-08-20
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    相关资源
    最近更新 更多