HttpOnly——防XSS攻击的方法之一

如果您在cookie中设置了HttpOnly属性,那么通过js脚本将无法读取到cookie信息,这样能有效的防止XSS攻击。

将cookie设置成HttpOnly是为了防止XSS攻击,窃取cookie内容,这样就增加了cookie的安全性,即便是这样,也不要将重要信息存入cookie。

如何在Java中设置cookie是HttpOnly呢?
Servlet 2.5 API 不支持 cookie设置HttpOnly
http://docs.oracle.com/cd/E17802_01/products/products/servlet/2.5/docs/servlet-2_5-mr2/

建议升级Tomcat7.0,它已经实现了Servlet3.0
http://tomcat.apache.org/tomcat-7.0-doc/servletapi/javax/servlet/http/Cookie.html

但是苦逼的是现实是,老板是不会让你升级的。
那就介绍另外一种办法:
利用HttpResponse的addHeader方法,设置Set-Cookie的值
cookie字符串的格式:key=value; Expires=date; Path=path; Domain=domain; Secure; HttpOnly

//设置cookie

response.addHeader("Set-Cookie", "uid=112; Path=/; HttpOnly");

//设置多个cookie

response.addHeader("Set-Cookie", "uid=112; Path=/; HttpOnly");

response.addHeader("Set-Cookie", "timeout=30; Path=/test; HttpOnly");

//设置https的cookie

response.addHeader("Set-Cookie", "uid=112; Path=/; Secure; HttpOnly");

具体实现代码:

package com.comp.shp.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CookieFilter implements Filter {

	private static final Logger LOGGER = LoggerFactory.getLogger(CookieFilter.class);
	
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    	LOGGER.info("CookieFilter init");
    }

    @Override
    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];
            String value = cookie.getValue();
            StringBuilder builder = new StringBuilder();
            builder.append("JSESSIONID=" + value + "; ");
            builder.append("HttpOnly; ");
            resp.setHeader("Set-Cookie", builder.toString());
        }
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    	LOGGER.info("CookieFilter destroy");
    }

}
 然后在web.xml里添加该过滤器: 
<filter>
		<filter-name>cookieFilter</filter-name>  
		<filter-class>com.comp.shp.web.filter.CookieFilter</filter-class>  
	</filter>
	<filter-mapping>
		<filter-name>cookieFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>