2015-04-02 297 views
1

我需要限制对包含会话令牌的cookie的访问,以便javascript无法访问它。 给出的建议是在Cookie上设置Secure和HttpOnly标志。在Spring MVC控制器中创建的Cookie上设置http-only

我在使用@ResponseBody时没有设置Cookie,所以我在Cookie中设置了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; 
    } 

如Chrome浏览器控制台中显示,安全设置,而不是http

Showing that secure flag is being set

我已经尝试添加参数下的servlet到web.xml 3.0规格说明,允许安全和HTTP - 只能设置会话cookie,但因为我需要自己处理会话(Spring MVC应用程序需要保持无状态),所以这对我不起作用。

更新:

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

回答

3

它可以设置为cookie.setHttpOnly(true)就像您为了安全一样。

+0

让我试着加大了Servlet规范到3 – 2015-04-02 06:26:01

+0

我没有使用自旋微观MVC框架,但是这适用于Java servlet。是'javax.servlet.http.Cookie'使用的'Cookie'吗? – wolfram77 2015-04-02 06:26:11

+0

这是正确的:javax.servlet.http.Cookie;从哪个servlet版本设置Http只支持? – 2015-04-02 06:33:48

0

替换:

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

具有以下

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

这可能会实现。

+0

这只是将值设置为“1427955447675 Http-Only” – 2015-04-02 06:18:39

+0

是的,我错过了把;正如你所说,这也行不通。我可以知道你使用的服务器吗?因为某些服务器级别的配置可能会导致冲突 – 2015-04-02 06:28:15

0

您需要设置HttpOnly如下:

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

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

+0

我在Chrome控制台中看到的值现在是“142795578​​9419”,但没有设置HTTP标志 – 2015-04-02 06:23:50

+0

您的意思是说在上述更改之后,您仍然没有看到'HttpOnly'? – Mithun 2015-04-02 06:26:21

相关问题