cookie 设置 httpOnly属性

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cookie 设置 httpOnly属性相关的知识,希望对你有一定的参考价值。

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;
/**
 * 
* <P>CookieにHTTPOnly属性を設定インターセプタークラス.</P>
*
* @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中配置拦截器

<filter>
   <filter-name>CookieHttpOnly</filter-name>
   <filter-class>jp.co.univ.www.admin.filter.CookieHttpOnlyFilter</filter-class>
   </filter>
<filter-mapping>
   <filter-name>CookieHttpOnly</filter-name>
   <url-pattern>/*</url-pattern>
   </filter-mapping>


技术分享

参考:

http://conkeyn.iteye.com/blog/2025484


http://blog.csdn.net/a19881029/article/details/27536917


以上是关于cookie 设置 httpOnly属性的主要内容,如果未能解决你的问题,请参考以下文章

用javascript能不能提取httponly属性的cookie

cookie设置httponly属性防护XSS攻击

Tomcat为Cookie设置HttpOnly属性

JAVA设置HttpOnly Cookies

设置了HttpOnly属性的COOKIES用DELPHI怎么访问

SessionCookie(httpOnly,secure)Token