cookie 设置 httpOnly属性
发表于:2024-11-25 作者:热门IT资讯网编辑
编辑最后更新 2024年11月25日,cookie 设置 httpOnly属性防止js读取cookie.建立filter拦截器类CookieHttpOnlyFilterimport java.io.IOException;import j
cookie 设置 httpOnly属性防止js读取cookie.
建立filter拦截器类
CookieHttpOnlyFilter
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;/** * *CookieにHTTPOnly属性を設定インターセプタークラス.
** @author hnnc* @author $Author$* @version $Id$ */public class CookieHttpOnlyFilter implements Filter { /** {@inheritDoc} **/ 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=/admin; HttpOnly"); // httpsの设置// httpResp.addHeader("Set-Cookie", "JSESSIONID=" + sessionId// + "; Path=/admin;Secure; HttpOnly"); } } } chain.doFilter(httpReq, httpResp); } /** {@inheritDoc} **/ public void destroy() { } /** {@inheritDoc} **/ public void init(FilterConfig filterConfig) throws ServletException { }}
web.xml中配置拦截器
CookieHttpOnly jp.co.univ.www.admin.filter.CookieHttpOnlyFilter CookieHttpOnly /*
参考:
http://conkeyn.iteye.com/blog/2025484
http://blog.csdn.net/a19881029/article/details/27536917