Spring Session - WebFlux with Custom Cookie
本指南介绍了如何在基于 WebFlux 的应用程序中配置 Spring Session 以使用自定义 cookie。本指南假设您已使用所选数据存储在项目中设置 Spring Session。例如, HttpSession with Redis。
This guide describes how to configure Spring Session to use custom cookies in a WebFlux based application. The guide assumes you have already set up Spring Session in your project using your chosen data store. For example, HttpSession with Redis.
您可以在WebFlux Custom Cookie sample application中找到已完成指南。 |
You can find the completed guide in the webflux-custom-cookie-sample. |
Spring Boot Configuration
设置好 Spring Session 后,你可以公开一个 WebSessionIdResolver
作为 Spring Bean 自定义会话 Cookie 的写入方式。Spring Session 默认使用 CookieWebSessionIdResolver
。将 WebSessionIdResolver
作为 Spring Bean 公开可以在使用 @EnableRedisHttpSession
等配置时增强现有配置。以下示例展示了如何自定义 Spring Session 的 cookie:
Once you have set up Spring Session, you can customize how the session cookie is written by exposing a WebSessionIdResolver
as a Spring bean.
Spring Session uses a CookieWebSessionIdResolver
by default.
Exposing the WebSessionIdResolver
as a Spring bean augments the existing configuration when you use configurations like @EnableRedisHttpSession
.
The following example shows how to customize Spring Session’s cookie:
Unresolved include directive in modules/ROOT/pages/guides/boot-webflux-custom-cookie.adoc - include::example$spring-session-samples/spring-session-sample-boot-webflux-custom-cookie/src/main/java/sample/CookieConfig.java[]
1 | We customize the name of the cookie to be JSESSIONID . |
2 | We customize the path of the cookie to be / (rather than the default of the context root). |
3 | We customize the SameSite cookie directive to be Strict . |
webflux-custom-cookie
Sample Application
本节描述了如何使用 webflux-custom-cookie
示例应用程序。
This section describes how to work with the webflux-custom-cookie
sample application.
Running the webflux-custom-cookie
Sample Application
您可以获取 源代码 并调用以下命令运行示例:
You can run the sample by obtaining the source code and invoking the following command:
$ ./gradlew :spring-session-sample-boot-webflux-custom-cookie:bootRun
要让示例发挥作用,你必须在 localhost 上 install Redis 2.8+ 并使用默认端口 (6379) 运行它。或者,你可以更新 |
For the sample to work, you must install Redis 2.8+ on localhost and run it with the default port (6379).
Alternatively, you can update the |
您现在应该能够访问 [role="bare"][role="bare"]http://localhost:8080/ 中的应用程序。
You should now be able to access the application at [role="bare"]http://localhost:8080/
Exploring the webflux-custom-cookie
Sample Application
现在你可以使用此应用程序。填写以下信息的表单:
Now you can use the application. Fill out the form with the following information:
-
Attribute Name: username
-
Attribute Value: rob
现在,点击 Set Attribute 按钮。现在,你应该能看到表中显示的值了。
Now click the Set Attribute button. You should now see the values displayed in the table.
如果你查看该应用程序的 cookie,将能看到 cookie 已保存到自定义名称 JSESSIONID
。
If you look at the cookies for the application, you can see the cookie is saved to the custom name of JSESSIONID
.