すべてのプロダクト
Search
ドキュメントセンター

ApsaraDB for MongoDB:MongoDB driver 用の SSL 接続サンプルコード

最終更新日:Feb 17, 2025

このトピックでは、クライアントからApsaraDB for MongoDBデータベースへのSSL接続を確立する方法について説明します。 これにより、送信中のデータのプライバシーとセキュリティが保証されます。

ApsaraDB for MongoDBデータベースにアクセスするためのSSL接続を確立する場合、クライアントは認証機関 (CA) 証明書を提供しません。 ただし、サーバー証明書を検証し、ホスト名の検証を無視するようにCAを構成する必要があります。

SSL暗号化の設定方法の詳細については、「インスタンスのSSL暗号化の設定」をご参照ください。

Node.js

Node.jsを使用してApsaraDB For MongoDBデータベースへのSSL接続を確立する方法の詳細については、「MongoDB Node.js Driver」をご参照ください。

サンプルコード

MongoDBクライアントURIの末尾に /?ssl = trueを追加し、sslCAをCA証明書のパスに設定してから、ホスト名の検証を無視するためにcheckServerIndentityをfalseに設定します。

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

PHPを使用してApsaraDB For MongoDBデータベースへのSSL接続を確立する方法の詳細については、「MongoDB PHP Driver」をご参照ください。

サンプルコード

MongoDB\Client ::__ constructを使用して、$uri、$uriOptions、および $driverOptionsのパラメーターグループを使用してクライアントインスタンスを作成します。

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

$uriOptions で、ssl を true に設定して SSL 接続を有効にします。 $driverOptions で、ca_file を CA 証明書のパスに設定します。 ホスト名の検証を無視するには、allow_invalid_hostnameをtrueに設定します。 $uriOptions で、ssl を true に設定して SSL 接続を有効にします。 $driverOptions で、ca_file を CA 証明書のパスに設定します。 ホスト名の検証を無視するには、allow_invalid_hostnameをtrueに設定します。

<?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

Javaを使用してApsaraDB For MongoDBデータベースへのSSL接続を確立する方法の詳細については、「MongoDB Node.js Driver」をご参照ください。

サンプルコード

MongoClientOptions で、sslEnabled を true に設定して SSL 接続を有効にします。 ホスト名の検証を無視するには、sslInvalidHostNameAllowedをtrueに設定します。

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

keytool コマンドを実行して CA 証明書を指定します。

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

Java Virtual Machine (JVM) システムのプロパティを設定して、正しい信頼ストアとパスワードストアを指定します。

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

Python

Pythonを使用してApsaraDB For MongoDBデータベースへのSSL接続を確立する方法の詳細については、「MongoDB Python Driver」をご参照ください。

サンプルコード

ssl接続を有効にするにはSSLをTrueに設定し、CA証明書のパスにssl_ca_certsを設定し、ホスト名の検証を無視するにはssl_match_hostnameをFalseに設定します。

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

Cを使用してApsaraDB For MongoDBデータベースへのSSL接続を確立する方法の詳細については、「MongoDB C Driver」をご参照ください。

サンプルコード

MongoDBクライアントURIの末尾に /?ssl = trueを追加します。 mongoc_ssl_opt_t を使用して SSL オプションを設定し、ca_file を CA 証明書のパスに設定します。 ホスト名の検証を無視するには、allow_invalid_hostnameをfalseに設定します。

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++

C ++ を使用してApsaraDB For MongoDBデータベースへのSSL接続を確立する方法の詳細については、「MongoDB C ++ ドライバー」をご参照ください。

サンプルコード

MongoDBクライアントURIの末尾に /?ssl = trueを追加します。 mongocxx::options::ssl を使用して SSL パラメータを設定し、ca_file を CA 証明書のパスに設定します。

説明

MongoDB C ++ ドライバーのホスト名検証を無視することはできません。

#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

Scalaを使用してApsaraDB For MongoDBデータベースへのSSL接続を確立する方法の詳細については、「MongoDB Scala Driver」をご参照ください。

サンプルコード

MongoDB Scalaドライバーは、Nettyが提供する基盤となるSSLを使用して、MongoDBサーバーへのSSL接続をサポートします。 MongoClientSettingsで、sslEnabledをtrueに設定してSSL接続を有効にし、sslInvalidHostNameAllowedをtrueに設定してホスト名の検証を無視します。

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")
                

keytool コマンドを実行して CA 証明書を指定します。これは Java の方法と同じです。

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

Java Virtual Machine (JVM) システムのプロパティを設定して、正しい信頼ストアとパスワードストアを指定します。

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

Golang

Golangを使用してApsaraDB For MongoDBデータベースへのSSL接続を確立する方法の詳細については、「MongoDB Golang Driver」および「Crypto tlsパッケージ」をご参照ください。

サンプルコード

MongoDB Golangドライバーは、Nettyが提供する基盤となるSSLを使用して、MongoDBサーバーへのSSL接続をサポートします。 設定を使用して SSL オプションを設定します。 RootCAを設定してCA証明書を指定し、InsecureSkipVerifyをtrueに設定してホスト名の検証を無視します。

package main

import (
    "context"
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
    "go.mongodb.org/mongo-driver/mongo/writeconcern"
    "io/ioutil"
    "log"
)

func main() {
    var filename = "ca.pem"
    rootPEM, err := ioutil.ReadFile(filename)
    roots := x509.NewCertPool()
    if ok := roots.AppendCertsFromPEM([]byte(rootPEM)); !ok {
        fmt.Printf("get certs from %s fail!\n", filename)
        return
    }
    tlsConfig := &tls.Config{
        RootCAs: roots,
        InsecureSkipVerify: true,
    }

    // Create a Client to a MongoDB server and use Ping to verify that the
    // server is running.
    // Set the database account to test and the database to admin. 
    clientOpts := options.Client().ApplyURI("mongodb://test:****@dds-bp*******1.mongodb.rds.aliyuncs.com:3717,dds-bp*******2.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-XXXXX&ssl=true")
    clientOpts.SetReadPreference(readpref.Secondary())
    clientOpts.SetWriteConcern(writeconcern.New(writeconcern.WMajority(), writeconcern.J(true), writeconcern.WTimeout(1000)))
    clientOpts.SetTLSConfig(tlsConfig)
    client, err := mongo.Connect(context.TODO(), clientOpts)
    if err != nil {
        fmt.Println("connect failed!")
        log.Fatal(err)
        return
    }
    fmt.Println("connect successful!")

    defer func() {
        if err = client.Disconnect(context.TODO()); err != nil {
            fmt.Println("disconnect failed!")
            log.Fatal(err)
        }
        fmt.Println("disconnect successful!")
    }()

    // Call Ping to verify that the deployment is up and the Client was
    // configured successfully. As mentioned in the Ping documentation, this
    // reduces application resiliency as the server may be temporarily
    // unavailable when Ping is called.
    if err = client.Ping(context.TODO(), nil); err != nil {
        fmt.Println("ping failed!")
        log.Fatal(err)
        return
    }
    fmt.Println("ping successful!")

    collection := client.Database("baz").Collection("qux")
    res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
    if err != nil {
        fmt.Println("insert result failed!")
        log.Fatal(err)
        return
    }
    id := res.InsertedID
    fmt.Println("Id: ", id)
    fmt.Printf("insert result: %v\n", res)

    result := bson.M{}
    filter := bson.D{{"_id", res.InsertedID}}
    if err := collection.FindOne(context.Background(), filter).Decode(&result); err != nil {
        fmt.Println("find failed!")
        log.Fatal(err)
        return
    }

    fmt.Printf("result: %v\n", result)
}

. NETコア

  1. .NETをインストールします。詳細については、.NETのダウンロードをご参照ください。

  2. プロジェクトを作成し、プロジェクトディレクトリに移動します。

    dotnet new console -o MongoDB
    cd MongoDB
  3. 次のコマンドを実行して、MongoDB用の.NET Coreのドライバーパッケージをインストールします。

    dotnet add package mongocsharpdriver --version 2.11.5

サンプルコード:

using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using MongoDB.Bson;
using MongoDB.Driver;namespace dotnetCase
{
class Program
{
static void Main(string[] args)
{
// Specify the instance information. 
const string host1 = "dds-***********-pub.mongodb.rds.aliyuncs.com";
const int port1 = 3717;
const string host2 = "dds-***********-pub.mongodb.rds.aliyuncs.com";
const int port2 = 3717;
const string replicaSetName = "mgset-********"; // Delete this row for a sharded cluster instance. 
const string admin = "admin";
// Set the database account to test. 
const string userName = "test";
const string passwd = "********";        
try
        {
            // Set the host information for connection. 
            MongoClientSettings settings = new MongoClientSettings();
            List<MongoServerAddress> servers = new List<MongoServerAddress>();
            servers.Add(new MongoServerAddress(host1, port1));
            servers.Add(new MongoServerAddress(host2, port2));
            settings.Servers = servers;
            // Set the replica set instance name. Delete this row for a sharded cluster instance. 
            settings.ReplicaSetName = replicaSetName;
            // Set the timeout period to 3 seconds. 
            settings.ConnectTimeout = new TimeSpan(0, 0, 0, 3, 0);
            // Set the logon user and password. 
            MongoCredential credentials = MongoCredential.CreateCredential(admin, userName, passwd);
            settings.Credential = credentials;
            // Set the SSL information. 
            SslSettings sslSettings = new SslSettings{
                ClientCertificates = new[] {new X509Certificate("ca.pem")},
            };
            settings.UseTls = true;
            settings.AllowInsecureTls = true;
            settings.SslSettings = sslSettings;
            // Initialize the client. 
            MongoClient client = new MongoClient(settings);
        }
        catch (Exception e)
        {
            Console.WriteLine("connection failed:"+e.Message);
        }
    }
}
}