【问题标题】:Connecting to MongoDB from spring boot app using ssl使用 ssl 从 Spring Boot 应用程序连接到 MongoDB
【发布时间】:2017-07-10 08:57:15
【问题描述】:

我正在尝试使用 ssl 将我的 Spring Boot 应用程序连接到 mongodb。我按照此处描述的步骤操作,但它们对我不起作用。

https://www.compose.com/articles/how-to-connecting-to-compose-mongodb-with-java-and-ssl/

有什么想法吗?

谢谢阿莱姆

【问题讨论】:

    标签: mongodb ssl spring-boot


    【解决方案1】:

    我建议您在此处查看使用 MongoDB 访问数据https://spring.io/guides/gs/accessing-data-mongodb/ 以获取基本使用示例。 spring-boot-starter-data-mongodb 会让你走得很远,你需要做的是像这样配置一个 MongoClientOptions bean

        @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 进程启动时

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

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

    我使用这篇文章 Spring data mongodb, how to set SSL? 和这个 spring.io 指南作为参考。

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      如果你只是想将你的 spring boot 应用与 mongodb 连接起来,你可以使用 java 代码中的 keyStore 和 trustStore。所以你不必通过命令行添加你的证书。如果您使用云代工,您可以将您的应用程序与 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());
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-10-26
        • 2020-10-13
        • 2020-03-22
        • 2020-04-07
        • 1970-01-01
        • 2019-06-12
        • 2018-09-30
        • 2020-11-01
        • 1970-01-01
        相关资源
        最近更新 更多