如何使用 Spring 连接到需要身份验证的 MongoDB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10249816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Spring to connect to MongoDB which requires authentication
提问by Joly
I am using the below Spring configuration in order to connect to mongoDB
我正在使用以下 Spring 配置来连接到 mongoDB
<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
<constructor-arg name="mongo" ref="mongo"/>
<constructor-arg name="databaseName" value="${mongodb.dbname}"/>
</bean>
<bean class="com.mongodb.MongoURI" id="mongoUri">
<constructor-arg value="${mongodb.url}" />
</bean>
<bean class="com.mongodb.Mongo" id="mongo">
<constructor-arg ref="mongoUri" />
</bean>
where mongo.url=mongodb://<user>:<password>@<host>:27017
在哪里 mongo.url=mongodb://<user>:<password>@<host>:27017
However I'm getting an authetication error. My understanding was that MongoUI can take a URL in the above format.
但是,我收到身份验证错误。我的理解是 MongoUI 可以采用上述格式的 URL。
I know that mongoTemplate can accept userCredentials object however I would need to extract them from the URL first and i'm not sure how to do that in the configuration.
我知道 mongoTemplate 可以接受 userCredentials 对象,但是我需要先从 URL 中提取它们,我不确定如何在配置中执行此操作。
Any idea how can I change my config above to suppot this assuming mongo.url format cannot be changed?
知道如何更改上面的配置以支持此假设 mongo.url 格式无法更改吗?
回答by Joly
found the solution using Spring Expression Language
使用 Spring Expression Language 找到了解决方案
<bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate">
<constructor-arg name="mongo" ref="mongo"/>
<constructor-arg name="databaseName" value="${mongodb.dbname}"/>
<constructor-arg name="userCredentials" ref="mongoCredentials"/>
</bean>
<bean id="mongoCredentials" class="org.springframework.data.authentication.UserCredentials">
<property name="username" value="#{mongoURI.username}" />
<property name="password" value="#{new java.lang.String(mongoURI.password)}" />
</bean>
<bean class="com.mongodb.MongoURI" id="mongoURI">
<constructor-arg value="${mongodb.url}" />
</bean>
<bean class="com.mongodb.Mongo" id="mongo">
<constructor-arg ref="mongoURI" />
</bean>
回答by Lealem Admassu
If you want to add authntication using java config
如果要使用 java config 添加身份验证
@Configuration
@EnableMongoRepositories("path.to.your.repository")
public class MongoConfig extends AbstractMongoConfiguration
{
@Value("${mongodb.name}")
private String dbName;
@Value("${mongodb.host}")
private String host;
@Value("${mongodb.port}")
private Integer port;
@Value("${mongodb.username}")
private String userName;
@Value("${mongodb.password}")
private String password;
@Override
protected String getDatabaseName()
{
return this.dbName;
}
@Override
public Mongo mongo() throws Exception
{
return new MongoClient(this.host, this.port);
}
@Override
@Bean
public SimpleMongoDbFactory mongoDbFactory() throws Exception
{
return new SimpleMongoDbFactory(mongo(), getDatabaseName());
}
@Override
@Bean
public MongoTemplate mongoTemplate() throws Exception
{
final UserCredentials userCredentials = new UserCredentials(this.userName, this.password);
final MongoTemplate mongoTemplate = new MongoTemplate(mongo(), getDatabaseName(), userCredentials);
mongoTemplate.setWriteConcern(WriteConcern.SAFE);
return mongoTemplate;
}
}
回答by jmmut
To update @Lealem Admassu's answer for java config, in Mongo 3 they changed the API, and now it is recommended to use mongo's MongoCredentialsinstead of UserCredentials.
为了更新@Lealem Admassu 对 java 配置的回答,在 Mongo 3 中他们更改了 API,现在建议使用 mongo'sMongoCredentials而不是UserCredentials.
Here there is a simple example of how to get a MongoClient: http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.mongo-3.authentication
这里有一个如何获取 MongoClient 的简单示例:http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongo.mongo-3.authentication
The next code can be done modular, but more or less this works for me (I needed a MongoTemplate):
下一个代码可以模块化完成,但或多或少对我有用(我需要一个 MongoTemplate):
public MongoTemplate getMongoTemplate(String host, int port,
String authenticationDB,
String database,
String user, char[] password)
throws UnknownHostException {
return new MongoTemplate(
new SimpleMongoDbFactory(
new MongoClient(
new ServerAddress(host, port),
Collections.singletonList(
MongoCredential.createCredential(
user,
authenticationDB,
password
)
)
),
database
)
);
}

