欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

检测到会话cookie中缺少HttpOnly属性

程序员文章站 2022-07-05 23:13:51
...

解决方案01:在会话cookie中添加HttpOnly属性
具体操作步骤如下:

HttpServletResponse response2 = (HttpServletResponse)response;
response2.setHeader( "Set-Cookie", "name=value; HttpOnly");

检测到会话cookie中缺少HttpOnly属性
解决方案02(建议使用):在会话cookie中添加HttpOnly属性
具体操作步骤如下:
在项目中,com.gblfy.util包下,新建CookieFilter类
见附件:

package com.sinosoft.fis.util;

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 javax.servlet.http.HttpSession;

/**
 * 功能描述:
 * <p>
 *   1.Cookie 设置 httpOnly属性 Cookie 
 *   2.设置 httpOnly属性防止js读取cookie
 * </p>
 *
 * @author gblfy
 */
public class CookieHttpOnlyFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if (!(request instanceof HttpServletRequest)) {
			chain.doFilter(request, response);
			return;
		}
		HttpServletRequest httpReq = (HttpServletRequest) request;
		HttpServletResponse httpResp = (HttpServletResponse) response;
		Cookie[] cookies = httpReq.getCookies();
		if (cookies != null) {
			Cookie cookie = cookies[0];
			if (cookie != null) {
				HttpSession session = httpReq.getSession();
				if (session != null) {
					String sessionId = session.getId();
					// http设置
					httpResp.addHeader("Set-Cookie", "JSESSIONID=" + sessionId + "; Path=/fis; HttpOnly");
					// https设置
//	                    httpResp.addHeader("Set-Cookie", "JSESSIONID=" + sessionId
//	                            + "; Path=/admin;Secure; HttpOnly");
				}
			}
		}
		chain.doFilter(httpReq, httpResp);

	}

	public void destroy() {
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

}

在web.xml中添加拦截器

<filter>
    	<filter-name> CookieHttpOnly</filter-name>
    	<filter-class> com.sinosoft.fis.util. CookieHttpOnlyFilter</filter-class>
    </filter>
  <filter-mapping>
    	<filter-name> CookieHttpOnly</filter-name>
    	<url-pattern>/*</url-pattern>
    </filter-mapping>

火狐测试结果:
检测到会话cookie中缺少HttpOnly属性
谷歌测试结果:
检测到会话cookie中缺少HttpOnly属性
漏洞2参考连接:
https://blog.51cto.com/10926470/1921232
https://blog.csdn.net/a19881029/article/details/27536917

相关标签: BUG 缺少HttpOnly