如何通过直接处理 Http 标头来使用 HttpOnly 更新 cookie JSESSIONID?

发布于 2024-10-12 23:48:27 字数 676 浏览 4 评论 0原文

这是大局

我想将“HttpOnly”附加到 JSESSIONID Cookie,但我想手动执行此操作,意思是:

//create a new cookie
StringBuilder updatedCookie = new StringBuilder("JSESSIONID").append("=")
                .append(sessionId).append("; Path=").append("/")
                .append("; HttpOnly");

//save the cookie
response.setHeader("SET-COOKIE", updatedCookie.toString());

这是在映射到所有站点的 Servlet Filter 中完成的(过滤器的 url 模式为“/*”)

  1. 如何使该过滤器仅运行一次?也就是说,在登录时,或者
  2. 我是否真的必须在每个请求时运行并检查此 cookie 是否已被标记,如果答案为“是”则跳过?

有什么建议吗?

PS:

  1. 不要告诉我升级到Servlet 3.0,因为我现在做不到
  2. 忽略StringBuilder的不当使用和缺少变量sessionId

Here is the big picture

I want to append "HttpOnly" to the JSESSIONID Cookie, but I want to do this by hand, meaning:

//create a new cookie
StringBuilder updatedCookie = new StringBuilder("JSESSIONID").append("=")
                .append(sessionId).append("; Path=").append("/")
                .append("; HttpOnly");

//save the cookie
response.setHeader("SET-COOKIE", updatedCookie.toString());

This is done in a Servlet Filter, that is mapped to all the site (the filter has the url pattern as "/*")

  1. How can I make this filter run only once ? That is, at the login, or
  2. Do I really have to run at each request and check if this cookie has been already marked and skip if the answer is "yes" ?

Any suggestions ?

PS:

  1. Don't tell me to upgrade to Servlet 3.0 because I can't do that right now
  2. Ignore the improper use of the StringBuilder and missing variable sessionId

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

来日方长 2024-10-19 23:48:27

如何让这个过滤器只运行一次?即在登录时

不可能。会话可能已经预先创建。

理论上,你最好的地方是 HttpSessionListener#sessionCreated(),但这不会以任何方式向您提供 HttpServletResponse 对象,所以您迷路了。

我真的必须在每个请求时运行并检查此 cookie 是否已被标记,如果答案为“是”则跳过?

是的。然而,这应该特别便宜。

How can I make this filter run only once ? That is, at the login

Not possible. The session might already have been created beforehand.

In theory, your best place is HttpSessionListener#sessionCreated(), but this doesn't provide the HttpServletResponse object to you in any way, so you're lost.

Do I really have to run at each request and check if this cookie has been already marked and skip if the answer is "yes" ?

Yes. This should however be particularly cheap.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文