最近在解决XSS注入的问题,由于使用的servlet版本是2.5,不支持httpOnly的属性,故做了个工具类来实现cookie的httpOnly的功能。全类如下:
/**
* cookie工具类,解决servlet3.0以前不能添加httpOnly属性的问题
*
* @author zhang-long
* @createTime 2013-6-20
*/
public class CookieUtil {
/**
*
* @param response HttpServletResponse类型的响应
* @param cookie 要设置httpOnly的cookie对象
*/
public static void addHttpOnlyCookie(HttpServletResponse response, Cookie cookie){
// 判断对象是否存在null的情况
if(checkObjIsNull(response) || checkObjIsNull(cookie)){
return;
}
//依次取得cookie中的名称、值、最大生存时间、路径、域和是否为安全协议信息
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
int maxAge = cookie.getMaxAge();
String path = cookie.getPath();
String domain = cookie.getDomain();
boolean isSecure = cookie.getSecure();
StringBuffer strBufferCookie = new StringBuffer();
strBufferCookie.append(cookieName + "=" + cookieValue + ";");
if(maxAge >= 0){
strBufferCookie.append("Max-Age=" + cookie.getMaxAge() + ";");
}
if(!checkObjIsNull(domain)){
strBufferCookie.append("domain=" + domain + ";");
}
if(!checkObjIsNull(path)){
strBufferCookie.append("path=" + path + ";");
}
if(isSecure){
strBufferCookie.append("secure;HTTPOnly;");
}else{
strBufferCookie.append("HTTPOnly;");
}
response.addHeader("Set-Cookie",strBufferCookie.toString());
}
private static boolean checkObjIsNull(Object obj){
if(obj == null){
return true;
}
return false;
}
}
使用举例:
Cookie cookie1=new Cookie("n","cookieValue1");
cookie1.setMaxAge(500);
Cookie cookie2=new Cookie("cookieName2","cookieValue2");
Cookie cookie3=new Cookie("cookieName3","cookieValue3");
cookie3.setSecure(true);
Cookie cookie4=new Cookie("cookieName4","cookieValue4");
cookie4.setSecure(true);
CookieUtil.addHttpOnlyCookie(response, cookie1);
CookieUtil.addHttpOnlyCookie(response, cookie2);
CookieUtil.addHttpOnlyCookie(response, cookie3);
CookieUtil.addHttpOnlyCookie(response, cookie4);
例子中红色的部分只有在应用 使用了HTTPS协议的时候才能添加,否则这个cookie将再也无法读出!
添加成功后,查看cookie如下: