cookie 设置 httpOnly属性

发布时间:2020-03-31 15:39:11 作者:101ttyy
来源:网络 阅读:1405

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>


cookie 设置 httpOnly属性

参考:

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


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


推荐阅读:
  1. php7中如何设置COOKIE和销毁COOKIE
  2. ThinkPHP源码学习 cookie函数 设置 取值 删除

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

设置 cookie httponly

上一篇:如何判断linux服务器是虚拟机还是物理机

下一篇:一份关于Java开发Spring常见面试题及答案集合

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》