温馨提示×

温馨提示×

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

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

Cookie中怎么设置HttpOnly属性

发布时间:2021-07-23 14:41:31 来源:亿速云 阅读:2505 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关Cookie中怎么设置HttpOnly属性,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

利用拦截器实现,判断每次请求的响应是否包含SET-COOKIE头部,重写会话Cookie,添加需要的属性。虽较为生硬,但灵活性强。

新的规范API

新的规范添加SessionCookieConfig接口,用于操作会话Cookie,需要掌握以下主要方法:

setName(String name)
修改Session ID的名称,默认为"JSESSIONID"setDomain(String domain)
设置当前Cookie所处于的域
setPath(String path)
设置当前Cookie所处于的相对路径
setHttpOnly(boolean httpOnly)
设置是否支持HttpOnly属性
setSecure(boolean secure)

若使用HTTPS安全连接,则需要设置其属性为truesetMaxAge(int maxAge)设置存活时间,单位为秒如何使用呢,很方便,在ServletContextListener监听器初始化方法中进行设定即可;下面实例演示如何修改"JSESSIONID",以及添加支持HttpOnly支持:

全局设置Session-Cookie相交互部分属性@WebListenerpublic class SessionCookieInitialization implements ServletContextListener {private static final Log log = LogFactory
   .getLog(SessionCookieInitialization.class);public void contextInitialized(ServletContextEvent sce) {
  log.info("now init the Session Cookie");
  ServletContext servletContext = sce.getServletContext();
  SessionCookieConfig sessionCookie = servletContext
    .getSessionCookieConfig();
  sessionCookie.setName("YONGBOYID");
  sessionCookie.setPath(servletContext.getContextPath());
  sessionCookie.setHttpOnly(true);
  sessionCookie.setSecure(false);
  log.info("name : " + sessionCookie.getName() + "\n" + "domain:"
    + sessionCookie.getDomain() + "\npath:"
    + sessionCookie.getPath() + "\nage:"
    + sessionCookie.getMaxAge());
  log.info("isHttpOnly : " + sessionCookie.isHttpOnly());
  log.info("isSecure : " + sessionCookie.isSecure());
}public void contextDestroyed(ServletContextEvent sce) {
  log.info("the context is destroyed !");
}

}需要通过ServletContext对象获得SessionCookieConfig对象,才能够进一步自定义session cookie的属性。

无论以前的硬编码还是新的API实现,目标都是一致的,所产生头部信息也是完全一致。

毫无疑问,后者更为方便快捷,省缺了显示的操作响应元数据。

对当前站点的第一次请求,很容易从响应头信息中看到Set-Cookie的属性值:

不同浏览器平台上测试

在Safari、IE8、Opera 11 一切都很正常

Firefox 3.6、Chrome 9.0,JSESSIONID会继续存在:

YONGBOYID=601A6C82D535343163B175A4FD5376EA; JSESSIONID=AA78738AB1EAD1F9C649F705E

在所有浏览器中,SESSION ID等于新设置的YONGBOYID值(若不相等,问题就严重了!)

在客户端JS无法获得正确的SESSIONI ID了。

Tomcat服务器内置支持

可以不用如上显示设置Cookie domain、name、HttpOnly支持,在conf/context.xml文件中配置即可:

<Context useHttpOnly="true", sessionCookieName="YONGBOYID", sessionCookieDomain="/servlet3" … >...</Context>

既然JAVA应用服务器本身支持会话Cookie设定,那就没有必要在程序代码中再次进行编码了。这是一个好的实践:不要重复造轮子。

这里给出一段测试Session重写的一段脚本:

<div style="margin: 40px; paddding: 10px"><div><a href="sessionCookieTest">正常连接</a></div><div><a href="<%=response.encodeURL("sessionCookieTest") %>">重定向连接</a></div></div>

关于Cookie中怎么设置HttpOnly属性就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

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

AI