仅对在Spring MVC控制器中创建的Cookie设置http [英] Set http-only on cookies created in Spring MVC Controller

查看:2650
本文介绍了仅对在Spring MVC控制器中创建的Cookie设置http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我在使用@ResponseBody时遇到了无法设置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 ().getTime())。toString());
cookie.setSecure(true);
//如何设置http-only标志?
httpServletResponse.addCookie(cookie);

return true;
}

如Chrome控制台中所示,已设置Secure, p>



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



更新:



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

解决方案

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


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

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.

解决方案

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

这篇关于仅对在Spring MVC控制器中创建的Cookie设置http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆