Spring数据mongodb,如何设置SSL?

时间:2017-01-05 18:26:42

标签: spring mongodb spring-data-mongodb

到目前为止,我没有找到关于这个主题的好解释/文档。

我正在使用

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

我的代码如下:

   @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);
   }

你知道我应该为此配置SSL吗?我可以允许无效证书吗?

等效的mongo命令行将是

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

5 个答案:

答案 0 :(得分:4)

如果您只想将Spring Boot应用程序与mongodb连接,则可以将keyStore和trustStore与Java代码一起使用。因此,您不必通过命令行添加证书。如果您使用的是Cloud Foundry,则可以将您的应用程序与mongodbServices连接,然后在System.getEnv(“ VCAP_SERVICES”)中拥有所需的所有凭据。

@Configuration
public class MongoConfiguration extends AbstractMongoConfiguration {
    private static Log logger = LogFactory.getLog(MongoConfiguration.class);
    @Value("${spring.data.mongodb.database}")
    private String defaultDatabase; //database you want to connect
    private String host;
    private int port;
    private String authenticationDb; //usually admin
    private String username;
    private char[] password;
    private String certificateDecoded; //your CA Certifcate decoded (starts with BEGIN CERTIFICATE)

    public MongoConfiguration() {
        //method for credentials initialization
    }

    //you can't set replicaset=replset in mongooptions so if you want set replicaset, you have to use 
    // customEditorConfigurer in combintaion with class that implementsPropertyEditorRegistrar
    @Bean
    public static CustomEditorConfigurer customEditorConfigurer(){
        CustomEditorConfigurer configurer = new CustomEditorConfigurer();
        configurer.setPropertyEditorRegistrars(
                new PropertyEditorRegistrar[]{new ServerAddressPropertyEditorRegistrar()});
        return configurer;
    }

    @Override
    protected String getDatabaseName() {
        return authenticationDb;
    }

    @Override
    @Bean
    public MongoClient mongoClient() {
        MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress(host, port)), mongoCredentials(), mongoClientOptions());
        return mongoClient;
    }

    @Bean
    public MongoClientOptions mongoClientOptions() {
        MongoClientOptions.Builder mongoClientOptions = MongoClientOptions.builder().sslInvalidHostNameAllowed(true).sslEnabled(true);
        try {
            InputStream inputStream = new ByteArrayInputStream(certificateDecoded.getBytes(StandardCharsets.UTF_8));
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate caCert = (X509Certificate) certificateFactory.generateCertificate(inputStream);

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null); // You don't need the KeyStore instance to come from a file.
            keyStore.setCertificateEntry("caCert", caCert);

            trustManagerFactory.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
            mongoClientOptions.sslContext(sslContext);
            mongoClientOptions.sslInvalidHostNameAllowed(true);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }

        return mongoClientOptions.build();
    }

    private MongoCredential mongoCredentials() {
        return MongoCredential.createCredential(username, authenticationDb, password);
    }

//With MongoTemplate you have access to db.
    @Bean
    public MongoTemplate mongoTemplate() {
        SimpleMongoDbFactory factory = new SimpleMongoDbFactory(mongoClient(), defaultDatabase);
        return new MongoClient(factory);

    }
}


public final class ServerAddressPropertyEditorRegistrar implements PropertyEditorRegistrar {
    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(ServerAddress[].class, new ServerAddressPropertyEditor());
    }
}

答案 1 :(得分:3)

文档中对此进行了解释:请参阅以下内容:

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

也可以使用以下配置启用它

    @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;
    }

将mongo客户端选项作为参数传递给MongoClient实例

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

使用

启动mongo进程时进一步添加

蒙戈     --ssl --sslAllowInvalidCertificates --host --port

连接到mongo进程的客户端不必设置任何选项来支持它。

答案 2 :(得分:0)

您还可以通过以下方式构建启用了ssl的mongo实例。

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

如果使用Spring Boot,则可以通过以下方式在application.properties或application.yml中对其进行配置

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

答案 3 :(得分:0)

Spring Boot 2.3.4和Eclipse中的Reactive Mongo:

  @Bean @Profile("dev")
  public MongoClientSettings mongoClientSettingsProd() throws NoSuchAlgorithmException{
    System.setProperty ("javax.net.ssl.keyStore","target/test-classes/xxx.pfx");
    System.setProperty ("javax.net.ssl.keyStorePassword","xxx");  
    SSLContext sslContext = SSLContext.getDefault();
    MongoClientSettings settings = MongoClientSettings.builder()
                                                      .applyToSslSettings(builder -> {
                                                        builder.enabled(true);
                                                        builder.context(sslContext);
                                                      })
                                                      .build();
    return settings;
  }

bootstrap.yml与x.509连接:

spring:
  data:
    mongodb:
      database: database_name #(Optional)
      uri: mongodb://CN=xxx.xxx.com@cloud.xxx.com:62017/?authMechanism=MONGODB-X509&tls=true&authSource=$external

答案 4 :(得分:0)

如下创建一个 Bean 并在需要的地方使用。

@Configuration
@ComponentScan(basePackages = "XXXXX")
@EnableMongoRepositories({ "XXXXXX" })
public class ApplicationConfig {
System.setProperty ("javax.net.ssl.keyStore", "<CERT>.keystore");
System.setProperty ("javax.net.ssl.keyStorePassword","<password>"); 

MongoCredential credential = MongoCredential.createMongoX509Credential(
            "C=US,ST=XXXXXXX,O=XXXXXX... "
            );
MongoClientSettings.Builder settings = MongoClientSettings.builder();
settings.credential(credential);
    
SSLContext sslContext = SSLContext.getDefault();
MongoClientSettings settings = MongoClientSettings.builder()
.applyToSslSettings(builder -> {
                builder.enabled(true);
                builder.context(sslContext);}).credential(credential).applyConnectionString(new     ConnectionString("mongodb://<host>:<port>/?authMechanism=MONGODB-X509&ssl=true"))
                                                      .build();
com.mongodb.client.MongoClient client = MongoClients.create(settings);
SimpleMongoClientDatabaseFactory factory = new     SimpleMongoClientDatabaseFactory(client, <database>);
MongoTemplate mongoTemplate = new MongoTemplate(factory);
return mongoTemplate;
    }
}