Spring Session - MongoDB Repositories
本指南介绍了如何使用基于 MongoDB 的 Spring Session。
This guide describes how to use Spring Session backed by MongoDB.
已完成的指南可在 mongo sample application 中找到。 |
The completed guide can be found in the mongo-sample. |
Updating Dependencies
在使用 Spring Session MongoDB 前,您必须确保更新您的依赖项。我们假设您正在使用可正常运行的 Spring Boot Web 应用程序。如果您使用的是 Maven,确保添加以下依赖项:
Before you use Spring Session MongoDB, you must ensure to update your dependencies. We assume you are working with a working Spring Boot web application. If you are using Maven, ensure to add the following dependencies:
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-mongodb</artifactId>
</dependency>
</dependencies>
Spring Configuration
在添加所需的依赖项后,我们可以创建我们的 Spring 配置。Spring 配置负责创建 Servlet Filter,该 Servlet Filter 使用由 Spring Session 支持的实现来替换 HttpSession
实现。
After adding the required dependencies, we can create our Spring configuration.
The Spring configuration is responsible for creating a Servlet Filter that replaces the HttpSession
implementation with an implementation backed by Spring Session.
您要做的就是添加以下 Spring 配置:
All you have to do is to add the following Spring Configuration:
Unresolved include directive in modules/ROOT/pages/guides/boot-mongo.adoc - include::example$spring-session-samples/spring-session-sample-boot-mongodb-traditional/src/main/java/org/springframework/session/mongodb/examples/config/HttpSessionConfig.java[]
1 | The @EnableMongoHttpSession annotation creates a Spring Bean with the name of springSessionRepositoryFilter that implements Filter.
This filter is what replaces the default HttpSession with the MongoDB-backed bean. |
2 | Configures the session timeout to 30 minutes. |
Configuring the MongoDB Connection
Spring Boot 自动创建 MongoClient
,它将 Spring Session 连接到本地主机上端口 27017(默认端口)的 MongoDB 服务器。在生产环境中,您需要确保更新您的配置,使其指向您的 MongoDB 服务器。例如,您可在 application.properties 中包含以下项:
Spring Boot automatically creates a MongoClient
that connects Spring Session to a MongoDB Server on localhost on port 27017 (default port).
In a production environment you need to ensure to update your configuration to point to your MongoDB server.
For example, you can include the following in your application.properties
spring.data.mongodb.host=mongo-srv spring.data.mongodb.port=27018 spring.data.mongodb.database=prod
如需了解更多信息,请参阅 Spring Boot 文档的“`HttpSession`到 MongoDB”({docs-url}/spring-boot/docs/current/reference/htmlsingle/#boot-features-connecting-to-mongodb)部分。
For more information, refer to {docs-url}/spring-boot/docs/current/reference/htmlsingle/#boot-features-connecting-to-mongodb[Connecting to MongoDB] portion of the Spring Boot documentation.
Servlet Container Initialization
我们的 Spring Configuration 创建了一个名为 springSessionRepositoryFilter
的 Spring Bean,该 Bean 实现 Filter
。springSessionRepositoryFilter
Bean 负责用由 Spring Session 支持的自定义实现替换 HttpSession
。
Our boot-mongo-configuration created a Spring Bean named springSessionRepositoryFilter
that implements Filter
.
The springSessionRepositoryFilter
bean is responsible for replacing the HttpSession
with a custom implementation that is backed by Spring Session.
为了让我们的 Filter
执行其魔力,Spring 需要加载我们的 Config
类。最后,我们需要确保我们的 Servlet 容器(即 Tomcat)对每个请求使用我们的 springSessionRepositoryFilter
。幸运的是,Spring Boot 为我们处理这两个步骤。
In order for our Filter
to do its magic, Spring needs to load our Config
class.
Last we need to ensure that our Servlet Container (i.e. Tomcat) uses our springSessionRepositoryFilter
for every request.
Fortunately, Spring Boot takes care of both of these steps for us.
MongoDB Sample Application
MongoDB 示例应用程序演示了如何使用 Spring Session 透明利用 MongoDB 来支持使用 Spring Boot 时 Web 应用程序的 HttpSession
。
The MongoDB Sample Application demonstrates how to use Spring Session to transparently leverage MongoDB to back a web application’s HttpSession
when using Spring Boot.
Running the MongoDB Sample Application
您可以获取 源代码 并调用以下命令运行示例:
You can run the sample by obtaining the source code and invoking the following command:
$ ./gradlew :samples:mongo:bootRun
您现在应该能够访问 [role="bare"][role="bare"]http://localhost:8080/ 中的应用程序。
You should now be able to access the application at [role="bare"]http://localhost:8080/
Exploring the security Sample Application
尝试使用该应用程序。输入以下内容以登录:
Try using the application. Enter the following to log in:
-
Username user
-
Password password
现在,单击 Login 按钮。你现在应该看到一条消息,指出你已使用之前输入的用户登录。用户的相关信息存储在 MongoDB 中,而不是 Tomcat 的 HttpSession
实现中。
Now click the Login button.
You should now see a message indicating your are logged in with the user entered previously.
The user’s information is stored in MongoDB rather than Tomcat’s HttpSession
implementation.
How does it work?
我们实际上是将值持久化到 Mongo 中,而不用使用 Tomcat 的 HttpSession
。Spring Session 用支持 Mongo 的实现替换了 HttpSession
。当 Spring Security 的 SecurityContextPersistenceFilter
将 SecurityContext
保存到 HttpSession
中时,它就会持久化到 Mongo 中。
Instead of using Tomcat’s HttpSession
, we are actually persisting the values in Mongo.
Spring Session replaces the HttpSession
with an implementation that is backed by Mongo.
When Spring Security’s SecurityContextPersistenceFilter
saves the SecurityContext
to the HttpSession
it is then persisted into Mongo.
当创建一个新的 HttpSession
时,Spring Session 会在你的浏览器中创建一个名为 SESSION 的 cookie,其中包含你会话的 id。继续,使用 Chrome 或 Firefox 查看 cookie(点击以获得帮助)。
When a new HttpSession
is created, Spring Session creates a cookie named SESSION in your browser that contains the id of your session.
Go ahead and view the cookies (click for help with Chrome or Firefox).
如果你愿意,可以使用 mongo 客户端轻松检查会话。例如,在基于 Linux 的系统上,可以输入:
If you like, you can easily inspect the session using mongo client. For example, on a Linux based system you can type:
示例应用程序使用内嵌式 MongoDB 实例,该实例侦听随机分配的端口。在应用程序启动期间会记录内嵌式 MongoDB 使用的端口,以及连接其的确切命令。 The sample application uses an embedded MongoDB instance that listens on a randomly allocated port. The port used by embedded MongoDB together with exact command to connect to it is logged during application startup. |
$ mongo --port … > use test > db.sessions.find().pretty()
或者,你还可以删除显式密钥。输入以下内容到你的终端,确保用 SESSION Cookie 的值替换 60f17293-839b-477c-bb92-07a9c3658843
:
Alternatively, you can also delete the explicit key. Enter the following into your terminal ensuring to replace 60f17293-839b-477c-bb92-07a9c3658843
with the value of your SESSION cookie:
db.sessions.remove({"_id":"60f17293-839b-477c-bb92-07a9c3658843"})
现在,再次访问 [role="bare"][role="bare"]http://localhost:8080/ 中的应用程序,并观察不再对我们进行身份验证的情况。
Now visit the application at [role="bare"]http://localhost:8080/ and observe that we are no longer authenticated.