如何使用Java连接到使用SSL和Auth启用的MongoDB

时间:2018-09-20 09:44:43

标签: java mongodb ssl-certificate mongodb-java-3.8

问题

我的CA证书为 cafile.pem ,PEM证书为 mongodb.pem 。我不确定如何在Java中使用它进行身份验证和连接MongoDB。任何建议将不胜感激。如果您想提供更多信息,请告诉我。

场景:

我正在使用 mongo-java-driver-3.4.3.jar 连接到已启用 SSL,已启用身份验证 MongoDB 3.7.9 >具有3个实例的分片集群。下面是我尝试连接到该服务器的Java代码。

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Starter {

    public static void main(String[] args){

        List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
        mongoCredentials.add(MongoCredential.
        createScramSha1Credential("admin", "admin", "admin".toCharArray()));

        List<ServerAddress> serverAddressArray = new ArrayList<ServerAddress>();

        serverAddressArray.add(new ServerAddress("xyz.domain.com", 27017));

        MongoClientOptions options = new MongoClientOptions.Builder()
                                        .sslInvalidHostNameAllowed(false)
                                        .sslEnabled(true)
                                        .readPreference(ReadPreference.primaryPreferred())
                                        .build();
        MongoClient mongoClient = new MongoClient(serverAddressArray, mongoCredentials, options);
        try {
            System.out.println("----- Step 1 ------");
            MongoDatabase db = mongoClient.getDatabase("CIM");
            System.out.println("----- Step 2 ------");
            MongoCollection<Document> collection = db.getCollection("orders");
            System.out.println("No of Documents in orders collection: " + collection.count());
          } catch (Exception ex) {
              System.out.println(ex.getMessage());
          }
    }       
}

我遇到错误;

----- Step 1 ------
----- Step 2 ------
Sep 20, 2018 2:48:02 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by ReadPreferenceServerSelector{readPreference=ReadPreference{name=primaryPreferred}} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=torvm-core16.sigma-systems.com:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Sep 20, 2018 2:48:03 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server xyz.domain.com:27017
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
    at com.mongodb.connection.SocketStream.read(SocketStream.java:88)
    at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:494)
    at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:224)
    at com.mongodb.connection.CommandHelper.receiveReply(CommandHelper.java:134)
    at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:121)
    at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
    .............

无论如何,我都能按照以下RoboMongo3T中的配置连接MongoServer。

enter image description here

mongodb.pem

Bag Attributes
    localKeyID: AA 4A 8D C5 AC CE 7A 08 F6 F1 00 2C 78 20 8D 0C 51 DE 66 F5 
subject=/OU=Domain Control Validated/CN=*.xyz.com
issuer=/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./OU=http://certs.godaddy.com/repository//CN=Go Daddy Secure Certificate Authority - G2
-----BEGIN CERTIFICATE-----
MIIFPzCCBCegAwIBAgIJAKpTjrMr7rpZMA0GCSqGSIb3DQEBCwUAMIG0MQswCQYD
.
.
.
-----END CERTIFICATE-----
Bag Attributes: <No Attributes>
subject=/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./OU=http://certs.godaddy.com/repository//CN=Go Daddy Secure Certificate Authority - G2
issuer=/C=US/ST=Arizona/L=Scottsdale/O=GoDaddy.com, Inc./CN=Go Daddy Root Certificate Authority - G2
-----BEGIN CERTIFICATE-----
MIIFPzCCBCegAwIBAgIJAKpTjrMr7rpZMA0GCSqGSIb3DQEBCwUAMIG0MQswCQYD
.
.
.
-----END CERTIFICATE-----
Bag Attributes
    localKeyID: AA 4A 8D C5 AC CE 7A 08 F6 F1 00 2C 78 20 8D 0C 51 DE 66 F5 
Key Attributes: <No Attributes>
-----BEGIN PRIVATE KEY-----
MIIFPzCCBCegAwIBAgIJAKpTjrMr7rpZMA0GCSqGSIb3DQEBCwUAMIG0MQswCQYD
.
.
.
-----END PRIVATE KEY-----

cafile.pem

-----BEGIN CERTIFICATE-----
MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh
.
.
.
.
.

-----END CERTIFICATE-----

1 个答案:

答案 0 :(得分:0)

  1. 我首先使用命令openssl pkcs12 -export -out mongodb.pkcs12 -in mongodb.pem创建了一个 mongodb.pkcs12 文件。
  2. 我必须将此文件包含在以下代码的 keyStore trustStore 的文件路径中(注意:我的代码包含也进行了更改和最小化。)

    import org.bson.Document;
    
    import com.mongodb.MongoClient;
    import com.mongodb.MongoClientURI;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoDatabase;
    
    public class Starter {
    
        private static MongoClient mongoClient;
    
        public static void main(String[] args) {
    
            System.setProperty("javax.net.ssl.trustStore", "mongodb.pkcs12");
            System.setProperty("javax.net.ssl.trustStorePassword", "yourPassword");
            System.setProperty("javax.net.ssl.keyStore", "mongodb.pkcs12");
            System.setProperty("javax.net.ssl.keyStorePassword", "yourPassword");
    
            MongoClientURI mongoClientURI = new MongoClientURI(
                    "mongodb://admin:admin@hostname3.xyz.com,hostname2.xyz.com:27017,hostname3.xyz.com:27017/admin?ssl=true");
            mongoClient = new MongoClient(mongoClientURI);
    
            try {
                MongoDatabase db = mongoClient.getDatabase("CIM");
                MongoCollection<Document> collection = db.getCollection("orders");
                System.out.println("No of Documents in orders collection: "
                        + collection.count());
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
    

上面的代码运行良好,下面是我得到的输出,

    Sep 24, 2018 3:49:13 PM com.mongodb.diagnostics.logging.JULLogger log
    INFO: Discovered cluster type of SHARDED
    Sep 24, 2018 3:49:15 PM com.mongodb.diagnostics.logging.JULLogger log
    INFO: Opened connection [connectionId{localValue:4}] to hostname3.xyz.com:27017
    No of Documents in orders collection: 3