Spring data mongodb, how to set SSL?

ε祈祈猫儿з 提交于 2019-12-07 15:58:55

问题


I have so far failed to find a good explanation/doc on the topic.

I am using

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.9.5.RELEASE</version>
</dependency>

and my code looks like this:

   @Bean
   public MongoClientFactoryBean mongo() {
      MongoClientFactoryBean mongo = new MongoClientFactoryBean();
      mongo.setHost(host);
      mongo.setPort(port);
      mongo.setCredentials(new MongoCredential[]{MongoCredential.createCredential(username, database, password.toCharArray())});
      return mongo;
   }

   @Bean
   public MongoTemplate mongoTemplate(Mongo mongo) throws Exception {
      return new MongoTemplate(mongo, database);
   }

Do you know how I should configure SSL for this? And can I allow invalid certificate?

The equivalent mongo command line would be

mongo --ssl --sslAllowInvalidCertificates --host <host> --port <port>

回答1:


It is explained in the docs : please refer below :

http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/ssl/?_ga=1.122423051.1001600813.1475930911

Also following configuration can be used to enable it

    @Bean
    public  MongoClientOptions mongoClientOptions(){
        System.setProperty ("javax.net.ssl.keyStore","<<PATH TO KEYSTOR >>");
        System.setProperty ("javax.net.ssl.keyStorePassword","PASSWORD");   
        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        MongoClientOptions options=builder.sslEnabled(true).build();        
        return options;
    }

pass the mongo client options to MongoClient instance as an argument

public MongoClient(ServerAddress addr, MongoClientOptions options) {
        super(addr, options);
    }

Adding further, when mongo processs is started with

mongo --ssl --sslAllowInvalidCertificates --host --port

clients connecting to the mongo process dont have to set any options to support this.




回答2:


You can also build the ssl enabled mongo instance in the following way.

public @Bean MongoClient mongoClient() throws Exception {
    return new MongoClient(new MongoClientURI("mongodb://username:password@host:port/db?ssl=true"));
}

If you using spring boot then it can be configurable in application.properties or application.yml in the following way

spring.data.mongodb.uri=mongodb://username:password@host:port/db?ssl=true


来源:https://stackoverflow.com/questions/41492113/spring-data-mongodb-how-to-set-ssl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!