ApsaraDB for MongoDB supports sslAllowConnectionsWithoutCertificates to allow you to establish SSL connections to MongoDB clients without a certificate. However, you must configure the CA to verify the server certificate and ignore host name verification.

For more information about how to configure SSL encryption, see Configure SSL encryption for an ApsaraDB for MongoDB instance.

Node.js

For more information, visit MongoDB Node.js Driver.

Sample code

Add /? ssl = true to the end of the MongoDB client URI, set sslCA to the path of the CA certificate, and set checkServerIndentity to false to ignore host name verification.

var MongoClient = require('mongodb').MongoClient,
  f = require('util').format,
  fs = require('fs');

// Read the certificate authority
var ca = [fs.readFileSync(__dirname + "/path/to/ca.pem")];

// Connect validating the returned certificates from the server
MongoClient.connect("mongodb://host01:27017,host02:27017,host03:27017/? replicaSet=myreplset&ssl=true", {
  server: {
      sslValidate:true,
      checkServerIdentity:false,#ignore host name validation
      sslCA:ca
  }
}, function(err, db) {
  db.close();
});

PHP

For more information, visit MongoDB Node.js Driver.

Sample code

Use MongoDB\Client::__construct to create the client instance, with three groups of parameters: $uri, $uriOptions, and $driverOptions.

function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])

In $uriOptions, set ssl to true to enable SSL connection. In $driverOptions, set ca_file to the path of the CA certificate. Set allow_invalid_hostname to true to ignore host name verification. In $uriOptions, set ssl to true to enable SSL connection. In $driverOptions, set ca_file to the path of the CA certificate. Set allow_invalid_hostname to true to ignore host name verification.

<? php
$client = new MongoDB\Client(
    'mongodb://host01:27017,host02:27017,host03:27017',
    [   'ssl' => true,
        'replicaSet' => 'myReplicaSet'
    ],
    [
        "ca_file" => "/path/to/ca.pem",
        "allow_invalid_hostname" => true

    ]
);
? >

Java

For more information, visit MongoDB Node.js Driver.

Sample code

In MongoClientOptions, set sslEnabled to true to enable SSL connection. Set sslInvalidHostNameAllowed to true to ignore host name verification.

import com.mongodb.MongoClientURI;
import com.mongodb.MongoClientOptions;
MongoClientOptions options
= MongoClientOptions.builder().sslEnabled(true).sslInvalidHostNameAllowed(true).build();
MongoClient client = new MongoClient("mongodb://host01:27017,host02:27017,host03:27017/? replicaSet=myreplset", options);

Run a keytool command to specify the CA certificate.

keytool -importcert -trustcacerts -file <path to certificate authority file> 
        -keystore <path to trust store> -storepass <password>

Set Java Virtual Machine (JVM) system properties to specify the correct trust store and password store.

System.setProperty("javax.net.ssl.trustStore","/trust/mongoStore.ts");
System.setProperty("javax.net.ssl.trustStorePassword","StorePass");

Python

For more information, visit MongoDB Python Driver.

Sample code

Set ssl to True to enable SSL connection, set ssl_ca_certs to the path of the CA certificate, and set ssl_match_hostname to False to ignore host name verification.

import ssl
from pymongo import MongoClient

uri = "mongodb://host01:27017,host02:27017,host03:27017/? replicaSet=myreplset"
client = MongoClient(uri,
                     ssl=True,
                     ssl_ca_certs='ca.pem',
                     ssl_match_hostname=False)

C

For more information, visit MongoDB C Driver.

Sample code

Add /? ssl = true to the end of the MongoDB client URI. Use mongoc_ssl_opt_t to set SSL options and set ca_file to the path of the CA certificate. Set allow_invalid_hostname to false to ignore host name verification.

mongoc_client_t *client = NULL;
client = mongoc_client_new (
      "mongodb://host01:27017,host02:27017,host03:27017/? replicaSet=myreplset&ssl=true");
const mongoc_ssl_opt_t *ssl_default = mongoc_ssl_opt_get_default ();
mongoc_ssl_opt_t ssl_opts = { 0 };

/* optionally copy in a custom trust directory or file; otherwise the default is used. */
memcpy (&ssl_opts, ssl_default, sizeof ssl_opts);
ssl_opts.ca_file = "/path/to/ca.pem"
ssl_opts.allow_invalid_hostname = false
mongoc_client_set_ssl_opts (client, &ssl_opts);

C++

For more information, visit MongoDB C++ Driver.

Sample code

Add /? ssl = true to the end of the MongoDB client URI. Use mongocxx::options::ssl to set SSL parameters and set ca_file to the path of the CA certificate.

Note You cannot ignore host name verification for the MongoDB C++ driver.
#include <mongocxx/client.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/options/client.hpp>
#include <mongocxx/options/ssl.hpp>

mongocxx::options::client client_options;
mongocxx::options::ssl ssl_options;

// If the server certificate is not signed by a well-known CA,
// you can set a custom CA file with the `ca_file` option.
ssl_options.ca_file("/path/to/ca.pem");

client_options.ssl_opts(ssl_options);

auto client = mongocxx::client{
    uri{"mongodb://host01:27017,host02:27017,host03:27017/? replicaSet=myreplset&ssl=true"}, client_opts};
				

Scala

For more information, visit MongoDB Scala Driver.

Sample code

The MongoDB Scala driver uses the underlying SSL provided by Netty to support SSL connections to MongoDB servers. In MongoClientOptions, set sslEnabled to true to enable SSL connection and set sslInvalidHostNameAllowed to true to ignore host name verification.

import org.mongodb.scala.connection.{ NettyStreamFactoryFactory, SslSettings}

MongoClientSettings.builder()
                   .sslSettings(SslSettings.builder()
                                           .enabled(true)                 
                                           .invalidHostNameAllowed(true)  
                                           .build())                      
                   .streamFactoryFactory(NettyStreamFactoryFactory())
                   .build()
val client: MongoClient = MongoClient("mongodb://host01:27017,host02:27017,host03:27017/? replicaSet=myreplset")
				

Run a keytool command to specify the CA certificate, which is the same as the method for Java.

keytool -importcert -trustcacerts -file <path to certificate authority file> 
        -keystore <path to trust store> -storepass <password>

Set JVM system properties to specify the correct trust store and password store.

System.setProperty("javax.net.ssl.trustStore","/trust/mongoStore.ts");
System.setProperty("javax.net.ssl.trustStorePassword","StorePass");

Golang

For more information, visit MongoDB Golang Driver and Crypto tls package.

Sample code

The MongoDB Golang driver uses the underlying SSL provided by Netty to support SSL connections to MongoDB servers. Use Config to set SSL options. Set RootCAs to specify the CA certificate and set InsecureSkipVerify to true to ignore host name verification.

import (
    "crypto/tls"
    "crypto/x509"
    "gopkg.in/mgo.v2
)
rootPEM, err := ioutil.ReadFile("path/to/ca.pem")
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(rootPEM)
tlsConfig := &tls.Config{
                  RootCAs: roots,
       InsecureSkipVerify: true
}
url := "mongodb://host01:27017,host02:27017,host03:27017/? replicaSet=myreplset&ssl=true"
dialInfo, err := ParseURL(url)
dialInfo.DialServer = func(addr *ServerAddr) (net.Conn, error) {
    return tls.Dial("tcp", addr.String(), tlsConfig)
}

session, err := DialWithInfo(dialInfo)
if err ! = nil {
    panic(err)
}
session.Close()