【发布时间】:2021-05-06 11:37:21
【问题描述】:
我正在使用 Spring WebFlux 和 Reactive MongoDB 开发一个 SaaS 项目。 它需要是一个多租户应用程序,并且每个租户都必须使用自己的数据库。
至于现在我只是将 Reactive MongoDB 依赖添加到 pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
然后我扩展了 AbstractReactiveMongoConfiguration 以提供 MongoClient 和 DatabaseName:
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration;
@Configuration
public class DatabaseConfiguration extends AbstractReactiveMongoConfiguration {
@Override
public MongoClient reactiveMongoClient() {
System.out.println("ReactiveMongoClient");
return MongoClients.create();
}
@Override
protected String getDatabaseName() {
System.out.println("DataBase name");
return "gateway";
}
}
整个应用程序是一个 OAuth 2.0 资源服务器,我能够从 ReactiveSecurityContextHolder 中的 Authentication 检索 TenantID。
public Mono<String> tenantID() {
return ReactiveSecurityContextHolder.getContext()
.switchIfEmpty(Mono.empty())
.flatMap((securityContext) -> {
Authentication authentication = securityContext.getAuthentication();
if (authentication instanceof CustomAuthenticationToken) {
CustomAuthenticationToken customAuthenticationToken = (customAuthenticationToken) authentication;
Jwt jwt = customAuthenticationToken.getToken();
String issuer = jwt.getIssuer().toString();
return Mono.justOrEmpty(issuer);
}
return Mono.empty();
});
}
为了根据执行请求的用户(身份验证)切换数据库,下一步是什么?
更新:
This 几乎接近目标,但差不多一年前@mp911de 说不可能。 想知道现在是否可行。 我怎样才能实现一个真正的反应式 ReactiveMongoDatabaseFactory 返回 Mono 以便我可以在返回 MongoDatabase 之前访问 SecurityContext,从而访问身份验证? p>
【问题讨论】:
-
不同的数据库是否属于同一个 mongodb 实例/集群并使用相同的数据库用户?还是您需要全新的连接?
-
对于第一个版本,可以使用相同的 mongodb 实例,但我至少需要使用用户凭据保护每个数据库。
标签: spring-data-mongodb spring-webflux multi-tenant