如何阻止Spring Boot添加会话cookie?

wor*_*joe 5 session url-rewriting spring-boot

我有一个 Spring Boot Web 应用程序,我正在尝试将其设为无状态。在我的 WebSecurityConfigurerAdapter 中我设置了

    http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
Run Code Online (Sandbox Code Playgroud)

但应用程序(使用 Thymeleaf 模板)通过;jsessionid=<some_session_id>在文件名后附加“”来不断重写图像和脚本的 URL。除了给我一个我不想要的 cookie 之外,它还有一个恼人的副作用,即 Spring Security 会阻止请求,因为它的 URL 中有分号!

Thymeleaf表示这是预期和期望的行为,并表示这不是他们的错:Thymeleaf 只是要求“Servlet API”重写 URL,而我们应该“在 Tomcat 上下文级别配置应用程序”来解决问题。

那么,我该怎么做呢?我有一个用于授权的自定义 JWT cookie,因此我根本不需要会话 cookie,当然在重写的 URL 中也不需要。

Man*_*uel 8

jsessionid行为与 STATELESS 无关。

最初,servlet 容器不知道客户端(浏览器)是否支持 cookie。

因此,在第一次请求页面时(通常是 HTTP GET):

  1. servlet 容器会将 附加;jsessionid=...到所有 URL。
  2. servlet 容器将(尝试)使用jsessionid.

当点击链接或提交公式(HTTP GET/POST)时,浏览器会将 cookie 发送回服务器,当且仅当浏览器确实首先接受了 cookie 设置。现在,servlet 容器可以识别是否jsessionid来自 cookie(通过 HTTP 请求标头传输)或 URL。

如果jsessionid源自 cookie,servlet 容器将停止将 附加;jsessionid=...到 URL。如果jsessionid源自您单击的 URL,它将继续将 附加;jsessionid=到所有 URL。

这与 STATELESS 或任何其他配置无关SessionCreationPolicy

查看 Spring Security 文档SessionCreationPolicy

/** Always create an {@link HttpSession} */
ALWAYS,
/**
 * Spring Security will never create an {@link HttpSession}, but will use the
 * {@link HttpSession} if it already exists
 */
NEVER,
/** Spring Security will only create an {@link HttpSession} if required */
IF_REQUIRED,
/**
 * Spring Security will never create an {@link HttpSession} and it will never use it
 * to obtain the {@link SecurityContext}
 */
STATELESS
Run Code Online (Sandbox Code Playgroud)

更新:

要通过 URL 禁用跟踪模式,请设置以下属性:

server.servlet.session.tracking-modes: COOKIE
Run Code Online (Sandbox Code Playgroud)

请参阅:https ://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html

  • 检查拼写。是“server.servlet...”还是“servlet.servlet...”? (2认同)