大家好,又见面了,我是你们的朋友全栈君。
描述:
1.会话cookie中缺少HttpOnly属性会导致攻击者可以通过程序(JS脚本、Applet等)获取到用户的cookie信息,造成用户cookie信息泄露,增加攻击者的跨站脚本攻击威胁。
2.HttpOnly是微软对cookie做的扩展,该值指定cookie是否可通过客户端脚本访问。Microsoft Internet Explorer 版本 6 Service Pack 1 和更高版本支持cookie属性HttpOnly。
3.如果在Cookie中没有设置HttpOnly属性为true,可能导致Cookie被窃取。窃取的Cookie可以包含标识站点用户的敏感信息,如ASP.NET会话ID或Forms身份验证票证,攻击者可以重播窃取的Cookie,以便伪装成用户或获取敏感信息,进行跨站脚本攻击等。
4.如果在Cookie中设置HttpOnly属性为true,兼容浏览器接收到HttpOnly cookie,那么客户端通过程序(JS脚本、Applet等)将无法读取到Cookie信息,这将有助于缓解跨站点脚本威胁。
解决方案:
CookieHttpOnlyFilter.java
-
package org._common.filter;
-
import java.io.IOException;
-
import java.text.SimpleDateFormat;
-
import java.util.Calendar;
-
import java.util.Date;
-
import java.util.Locale;
-
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;
-
/**
-
* 解决检测到会话cookie中缺少HttpOnly属性的问题
-
* @author kf0101
-
*
-
*/
-
public class CookieHttpOnlyFilter implements Filter {
-
public void destroy() {
-
}
-
public void doFilter(ServletRequest request, ServletResponse response,
-
FilterChain filterChain) throws IOException, ServletException {
-
// TODO Auto-generated method stub
-
HttpServletRequest req = (HttpServletRequest) request;
-
HttpServletResponse resp = (HttpServletResponse) response;
-
Cookie[] cookies = req.getCookies();
-
if(cookies!=null){
-
for(Cookie cookie : cookies){
-
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());
-
}
-
filterChain.doFilter(request, response);
-
}
-
}
-
public void init(FilterConfig arg0) throws ServletException {
-
// TODO Auto-generated method stub
-
}
-
}
web.xml:
-
<filter>
-
<filter-name>cookieHttpOnlyFilter</filter-name>
-
<filter-class>org._common.filter.CookieHttpOnlyFilter</filter-class>
-
</filter>
-
<filter-mapping>
-
<filter-name>cookieHttpOnlyFilter</filter-name>
-
<url-pattern>/*</url-pattern>
-
</filter-mapping>
验证方式:查看浏览器设置(HttpOnly) Set-Cookie: HttpOnly
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/148410.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...