首页 > 解决方案 > Spring 4 Session Cookie 更改字段

问题描述

我正在使用 Spring 4,并使用request.getSession()

我观察到创建了一个会话 cookie。响应头包含以下内容:

Set-Cookie: SESSION=ZTgwZWMxMDItOTA1MC00ZTZjLWIxMmUtZmM3NmQxNzJmNDBm; Path=/myApp/; Secure; HttpOnly

在创建的 Cookie 中,我需要 SameSite=Lax。目前,SameSite 没有价值。

所以在我的代码中,我做了以下尝试覆盖 SESSION cookie。

// request is of type HttpServletRequest
// response is of type HttpServletResponse
HttpSession session = request.getSession(); 
String base64value = Base64.getEncoder().encodeToString(session.getId().getBytes());
response.setHeader("Set-Cookie","SESSION=" + base64value + ";path=/myApp/ ;HttpOnly ;Secure;SameSite=lax");

但是现在创建了 2 个 SESSION cookie,并且可以在响应标头中看到:

Set-Cookie: SESSION=ZTgwZWMxMDItOTA1MC00ZTZjLWIxMmUtZmM3NmQxNzJmNDBm;path=/myApp/ ;HttpOnly ;Secure;SameSite=lax
Set-Cookie: SESSION=ZTgwZWMxMDItOTA1MC00ZTZjLWIxMmUtZmM3NmQxNzJmNDBm; Path=/myApp/; Secure; HttpOnly

我怎样才能在 Spring 4 中使用 SameSite=Lax 只有 1 个 SESSION cookie?

标签: javaspringtomcatcookiesspring-4

解决方案


您正在手动发送与Set-CookieSpring 会话管理设置的标头重复的标头。

如果 Spring 4 允许设置SameSite会话 cookie 的属性(不幸的是,我找不到这方面的文档,所以不能确定),那么我希望它在你的web.xml

<session-config>
    <cookie-config>
        <http-only>true</http-only>
        <secure>true</secure>
        <!-- Maybe there's a SameSite option? -->
    </cookie-config>
</session-config>

推荐阅读