# Spring Session-MongoDB 存储库
本指南描述了如何使用由 MongoDB 支持的 Spring Session 。
完整的指南可在Mongo 示例应用程序中找到。 |
---|
# 更新依赖项
在使用 Spring Session MongoDB 之前,必须确保更新依赖项。我们假设你正在使用一个有效的启动 Web 应用程序。如果你正在使用 Maven,请确保添加以下依赖项:
POM.xml
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-mongodb</artifactId>
</dependency>
</dependencies>
由于我们使用的是快照版本,因此我们需要确保添加 Spring 快照 Maven 存储库。确保在 POM.xml 中包含以下内容:
POM.xml
<repositories>
<!-- ... -->
<repository>
<id>spring-snapshot</id>
<url>https://repo.spring.io/libs-snapshot</url>
</repository>
</repositories>
# Spring 配置
在添加了所需的依赖关系之后,我们就可以创建我们的 Spring 配置了。 Spring 配置负责创建一个 Servlet 过滤器,该过滤器将HttpSession
实现替换为由 Spring Session 支持的实现。
你所要做的就是添加以下 Spring 配置:
@EnableMongoHttpSession (1)
public class HttpSessionConfig {
@Bean
public JdkMongoSessionConverter jdkMongoSessionConverter() {
return new JdkMongoSessionConverter(Duration.ofMinutes(30)); (2)
}
}
1 | @EnableMongoHttpSession 注释创建了一个名为springSessionRepositoryFilter 的 Spring Bean,它实现了 filter。这个 filter 用 MongoDB 支持的 Bean 替换了默认的 HttpSession 。 |
---|---|
2 | 将会话超时时间配置为 30 分钟。 |
# 配置 MongoDB 连接
Spring 引导会自动创建一个MongoClient
,它将 Spring Session 连接到端口 27017(默认端口)上的 LocalHost 上的 MongoDB 服务器。在生产环境中,你需要确保更新配置以指向 MongoDB 服务器。例如,你可以在应用程序.属性中包含以下内容
SRC/主/资源/应用程序.properties
spring.data.mongodb.host=mongo-srv
spring.data.mongodb.port=27018
spring.data.mongodb.database=prod
有关更多信息,请参阅 Spring 引导文档的连接到 MongoDB (opens new window)部分。
# Servlet 容器初始化
我们的Spring Configuration创建了一个名为springSessionRepositoryFilter
的 Spring Bean,它实现了Filter
。springSessionRepositoryFilter
Bean 负责用 Spring Session 支持的自定义实现替换HttpSession
。
为了让我们的Filter
发挥其魔力, Spring 需要加载我们的Config
类。最后,我们需要确保我们的 Servlet 容器(即 Tomcat)对每个请求使用我们的springSessionRepositoryFilter
。幸运的是,Boot 为我们解决了这两个步骤。
# MongoDB 示例应用程序
MongoDB 示例应用程序演示了如何在使用 Spring 引导时使用 Spring Session 透明地利用 MongoDB 来支持 Web 应用程序的HttpSession
。
# 运行 MongoDB 示例应用程序
你可以通过获取源代码 (opens new window)并调用以下命令来运行示例:
$ ./gradlew :samples:mongo:bootRun
现在你应该可以在http://localhost:8080/ (opens new window)上访问应用程序了。
# 探索安全示例应用程序
尝试使用该应用程序。输入以下内容即可登录:
用户 Name User
密码 密码
现在点击登录按钮。你现在应该会看到一条消息,表明你是用先前输入的用户登录的。用户的信息存储在 MongoDB 中,而不是 Tomcat 的HttpSession
实现中。
# 它是如何工作的?
而不是使用 Tomcat 的HttpSession
,我们实际上是在 Mongo 中持久化这些值。 Spring Session 用 Mongo 支持的实现替换HttpSession
。当 Spring Security 的SecurityContextPersistenceFilter
将SecurityContext
保存到HttpSession
时,它将被持久化到 Mongo 中。
当创建一个新的HttpSession
时, Spring Session 将在浏览器中创建一个名为会话的 cookie,其中包含会话的 ID。继续查看 cookies(单击Chrome (opens new window)或Firefox (opens new window)以获取帮助)。
如果你愿意,你可以使用 Mongo 客户机轻松地检查会话。例如,在基于 Linux 的系统上,你可以键入:
示例应用程序使用了一个嵌入式 MongoDB 实例,该实例监听随机分配的端口。 嵌入式 MongoDB 使用的端口以及用于连接到它的 Exact 命令在应用程序启动时记录。 |
---|
$ mongo --port ...
> use test
> db.sessions.find().pretty()
或者,你也可以删除显式密钥。在终端中输入以下内容,以确保用会话 cookie 的值替换60f17293-839b-477c-bb92-07a9c3658843
:
> db.sessions.remove({"_id":"60f17293-839b-477c-bb92-07a9c3658843"})
现在访问http://localhost:8080/ (opens new window)上的应用程序,并观察到我们不再经过身份验证。