java - Spring 4 Session Cookie 更改字段

标签 java spring tomcat cookies spring-4

我使用的是 Spring 4,并使用 request.getSession() 创建一个 session

我观察到创建了一个 session cookie。响应头包含如下:

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

在创建的 Cookie 中,我需要 SameSite=Lax。目前,SameSite 没有任何值(value)。

因此,在我的代码中,我执行了以下操作来尝试覆盖 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,并且可以在响应 header 中看到:

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

如何在 Spring 4 中只有 1 个带有 SameSite=Lax 的 SESSION cookie?

最佳答案

您正在手动发送 Set-Cookie header ,该 header 复制了 Spring session 管理设置的 header 。

如果 Spring 4 允许设置 session cookie 的 SameSite 属性(不幸的是,我找不到这方面的文档,所以无法确定),那么我希望它位于您的web.xml:

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

关于java - Spring 4 Session Cookie 更改字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59927012/

相关文章:

java - 卡在哈希表大小加倍的问题上

java - 通过 TCP 套接字的 Avro 通信

java - 未创建审核表

java - 部署/托管 Spring Boot 应用程序

java - 在 Tomcat 8.5.9 上部署 Spring 应用程序在本地主机访问日志中返回 404 1034 错误

java - Tomcat 后台线程启动两次?

java - CXF 3.1.12 无法创建安全的 XMLInputFactory

java - Spring - I18n - 通过静态类访问 MessageSource?

java - 具有不同类型 session 的 Spring Security

java - @WithUserDetails 注释不适用于 Spring 单元测试