Cookie设置HttpOnly属性,防止前端脚本更改cookie的XSS攻击

Tomcat版本为6.0.39,JDK版本为1.6update45

在Web工程上增加一个Filter对Cookie进行处理

    public class CookieFilter implements Filter {  
        public void doFilter(ServletRequest request, ServletResponse response,  
                FilterChain chain) throws IOException, ServletException {  
            HttpServletRequest req = (HttpServletRequest) request;  
            HttpServletResponse resp = (HttpServletResponse) response;  
      
            Cookie[] cookies = req.getCookies();  
      
            if (cookies != null) {  
                    Cookie cookie = cookies[0];  
                    if (cookie != null) {  
                        /*cookie.setMaxAge(3600); 
                        cookie.setSecure(true); 
                        resp.addCookie(cookie);*/  
                          
                        //Servlet 2.5不支持在Cookie上直接设置HttpOnly属性  
                        String value = cookie.getValue();  
                        StringBuilder builder = new StringBuilder();  
                        builder.append("JSESSIONID=" + value + "; ");  
                        builder.append("Secure; ");  
                        builder.append("HttpOnly; ");  
                        Calendar cal = Calendar.getInstance();  
                        cal.add(Calendar.HOUR, 1);  
                        Date date = cal.getTime();  
                        Locale locale = Locale.CHINA;  
                        SimpleDateFormat sdf =   
                                new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",locale);  
                        builder.append("Expires=" + sdf.format(date));  
                        resp.setHeader("Set-Cookie", builder.toString());  
                    }  
            }  
            chain.doFilter(req, resp);  
        }  
      
        public void destroy() {  
        }  
      
        public void init(FilterConfig arg0) throws ServletException {  
        }  
    }  
XML中的设置
  1. <filter>  
  2.     <filter-name>cookieFilterfilter-name>  
  3.     <filter-class>com.sean.CookieFilterfilter-class>  
  4. filter>  
  5.   
  6. <filter-mapping>  
  7.     <filter-name>cookieFilterfilter-name>  
  8.     <url-pattern>/*url-pattern>  
  9. filter-mapping> 
如果你已有过滤器,也可以将上述代码直接放在自己的过滤器里面 添加成功后,F12 查看网络-cookie 下方是否显示httponly 显示的话,说明设置成功。


你可能感兴趣的:(JAVA)