java 在 Spring MVC 控制器中创建的 cookie 上设置 http-only
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29406002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set http-only on cookies created in Spring MVC Controller
提问by Jan Vladimir Mostert
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.
我需要限制对包含会话令牌的 cookie 的访问,以便 javascript 无法访问它。给出的建议是在 cookie 上设置 Secure 和 HttpOnly 标志。
I was having trouble with cookies not being set when using @ResponseBody, so I'm setting the cookies inside a HandlerInterceptor.
我在使用 @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;
}
As shown in the chrome console, Secure is set, but not HTTP
如chrome控制台所示,设置了Secure,但没有设置HTTP
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.
我已经尝试在 servlet 3.0 sepcification 下向 web.xml 添加参数,允许在会话 cookie 上设置安全和 http-only,但由于我需要自己处理会话(Spring MVC 应用程序需要保持无状态),所以赢了不适合我。
Update:
更新:
I'm using Tomcat7, currently with Servlet 2.5 and Spring 3.2.8.
我正在使用 Tomcat7,目前使用 Servlet 2.5 和 Spring 3.2.8。
回答by wolfram77
It can be set as cookie.setHttpOnly(true)
just like you did for secure.
它可以cookie.setHttpOnly(true)
像您一样设置以确保安全。
回答by Mithun
You need to set the HttpOnly
as below:
您需要设置HttpOnly
如下:
Cookie cookie = new Cookie("timestamp", new Long(new Date().getTime()).toString() + ";HttpOnly");
It needs to follow cookieName=cookieValue;HttpOnly;Secure
format
它需要遵循cookieName=cookieValue;HttpOnly;Secure
格式
回答by sathya_dev
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.
这可能会奏效。