Spring Session - Custom Cookie
本指南描述了如何使用 Java 配置配置 Spring Session 以使用自定 cookie。本指南假定你已经使用你选择的数据库存储在你的项目中设置了 Spring Session。例如, HttpSession with Redis。
This guide describes how to configure Spring Session to use custom cookies with Java Configuration. The guide assumes you have already set up Spring Session in your project using your chosen data store. For example, HttpSession with Redis.
您可以在Custom Cookie sample application中找到已完成指南。 |
You can find the completed guide in the custom-cookie-sample. |
Spring Java Configuration
设置 Spring Session 后,您可以通过公开 CookieSerializer
(作为 Spring Bean)来自定义会话 Cookie 的写入方式。Spring Session 附带 DefaultCookieSerializer
。当您使用诸如 @EnableRedisHttpSession
的配置时,将 DefaultCookieSerializer
作为 Spring Bean 公开会增强现有配置。以下示例显示如何自定义 Spring Session 的 Cookie:
Once you have set up Spring Session, you can customize how the session cookie is written by exposing a CookieSerializer
as a Spring bean.
Spring Session comes with DefaultCookieSerializer
.
Exposing the DefaultCookieSerializer
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/java-custom-cookie.adoc - include::example$spring-session-samples/spring-session-sample-javaconfig-custom-cookie/src/main/java/sample/Config.java[]
1 | 我们自定义 cookie 名称,使其为 JSESSIONID 。 |
2 | We customize the name of the cookie to be JSESSIONID . |
3 | 我们自定义 cookie 路径,使其为 / (而不是默认的上下文根)。 |
4 | We customize the path of the cookie to be / (rather than the default of the context root). |
5 | 我们自定义域名模式(正则表达式),使其为 ^.?\\.(\\w\\.[a-z]+)$ 。这可以在多个域和应用程序之间共享会话。如果正则表达式不匹配,则不会设置域,并且会使用现有的域。如果正则表达式匹配,则第一个 grouping 将用作域。这意味着对 [role="bare"][role="bare"]https://child.example.com 的请求将域设置为 example.com 。然而,对 [role="bare"][role="bare"]http://localhost:8080/ 或 [role="bare"][role="bare"]https://192.168.1.100:8080/ 的请求会使 cookie 未设置,因此在开发中无需任何更改即可继续使用。 |
6 | We customize the domain name pattern (a regular expression) to be ^.?\\.(\\w\\.[a-z]+)$ .
This allows sharing a session across domains and applications.
If the regular expression does not match, no domain is set and the existing domain is used.
If the regular expression matches, the first grouping is used as the domain.
This means that a request to [role="bare"]https://child.example.com sets the domain to example.com .
However, a request to [role="bare"]http://localhost:8080/ or [role="bare"]https://192.168.1.100:8080/ leaves the cookie unset and, thus, still works in development without any changes being necessary for production. |
你应当只匹配有效的域名字符,因为域名会反映在响应中。这样做可以防止恶意用户实施攻击,比如 HTTP Response Splitting。
You should only match on valid domain characters, since the domain name is reflected in the response. Doing so prevents a malicious user from performing such attacks as HTTP Response Splitting.
Configuration Options
以下配置选项可供使用:
The following configuration options are available:
-
cookieName
:要使用的 cookie 名称。默认:SESSION
。 -
cookieName
: The name of the cookie to use. Default:SESSION
. -
useSecureCookie
:指定是否应使用安全 cookie。默认:创建时使用HttpServletRequest.isSecure()
的值。 -
useSecureCookie
: Specifies whether a secure cookie should be used. Default: Use the value ofHttpServletRequest.isSecure()
at the time of creation. -
cookiePath
:cookie 的路径。默认:上下文根。 -
cookiePath
: The path of the cookie. Default: The context root. -
cookieMaxAge
:指定创建会话时要设置的 cookie 的最大生存期。默认:-1
,表示在关闭浏览器时应删除 cookie。 -
cookieMaxAge
: Specifies the max age of the cookie to be set at the time the session is created. Default:-1
, which indicates the cookie should be removed when the browser is closed. -
jvmRoute
:指定要追加到会话 ID 中并在 cookie 中包含的后缀。用于标识应路由到哪个 JVM 来获得会话关联性。对于某些实现(即 Redis),此选项不提供性能优势。然而,它可以帮助跟踪特定用户的日志。 -
jvmRoute
: Specifies a suffix to be appended to the session ID and included in the cookie. Used to identify which JVM to route to for session affinity. With some implementations (that is, Redis) this option provides no performance benefit. However, it can help with tracing logs of a particular user. -
domainName
:允许指定要用于 cookie 的特定域名。这个选项易于理解,但通常需要开发环境和生产环境之间的不同配置。将domainNamePattern
视为一种替代方案。 -
domainName
: Allows specifying a specific domain name to be used for the cookie. This option is simple to understand but often requires a different configuration between development and production environments. SeedomainNamePattern
as an alternative. -
domainNamePattern
:不区分大小写的模式,用于从HttpServletRequest#getServerName()
中提取域名。模式应提供一个单独的分组,该分组用于提取 cookie 域的值。如果正则表达式不匹配,则不会设置域,并且会使用现有的域。如果正则表达式匹配,则第一个 grouping 将用作域。 -
domainNamePattern
: A case-insensitive pattern used to extract the domain name from theHttpServletRequest#getServerName()
. The pattern should provide a single grouping that is used to extract the value of the cookie domain. If the regular expression does not match, no domain is set and the existing domain is used. If the regular expression matches, the first grouping is used as the domain. -
sameSite
:用于SameSite
cookie 指令的值。若要禁用SameSite
cookie 指令的序列化,可以将此值设为null
。默认:Lax
-
sameSite
: The value for theSameSite
cookie directive. To disable the serialization of theSameSite
cookie directive, you may set this value tonull
. Default:Lax
你应当只匹配有效的域名字符,因为域名会反映在响应中。这样做可以防止恶意用户实施攻击,比如 HTTP Response Splitting。
You should only match on valid domain characters, since the domain name is reflected in the response. Doing so prevents a malicious user from performing such attacks as HTTP Response Splitting.
custom-cookie
Sample Application
本部分介绍如何使用 custom-cookie
示例应用程序。
This section describes how to work with the custom-cookie
sample application.
Running the custom-cookie
Sample Application
您可以获取 源代码 并调用以下命令运行示例:
You can run the sample by obtaining the source code and invoking the following command:
$ ./gradlew :spring-session-sample-javaconfig-custom-cookie:tomcatRun
要让示例发挥作用,你必须在 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 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
.