Php/docs/mongo.connecting.ssl

提供:Dev Guides
< Php
移動先:案内検索

SSL での接続

このドライバは » MongoDB over SSL 接続に対応しています。また、オプションで SSL ストリームコンテキスト を使えば、 指定した証明書チェーンによる証明書の検証や、 » X509 証明書による MongoDB への接続といった機能も利用できます。

例1 SSL を使った MongoDB インスタンスへの接続

<?php$mc = new MongoClient("mongodb://server1", array("ssl" => true));?>

例2 SSL を使った MongoDB インスタンスへの接続と、証明書の検証

<?php$SSL_DIR = "/vagrant/certs";$SSL_FILE = "CA_Root_Certificate.pem";$ctx = stream_context_create(array(    "ssl" => array(        /* Certificate Authority the remote server certificate must be signed by */        "cafile"            => $SSL_DIR . "/" . $SSL_FILE,        /* Disable self signed certificates */        "allow_self_signed" => false,        /* Verify the peer certificate against our provided Certificate Authority root certificate */        "verify_peer"       => true, /* Default to false pre PHP 5.6 */        /* Verify the peer name (e.g. hostname validation) */        /* Will use the hostname used to connec to the node */        "verify_peer_name"  => true,        /* Verify the server certificate has not expired */        "verify_expiry"     => true, /* Only available in the MongoDB PHP Driver */    ),);$mc = new MongoClient(    "mongodb://server1",     array("ssl" => true),     array("context" => $ctx));?>

注意:

"verify_peer_name" は PHP 5.6.0 で導入されました。 しかし、MongoDB ドライバの 1.6.5 以降ではこの機能をドライバ自身にバックポートして組み込んでいるので、 PHP 5.3 や 5.4 でも使えます。

例3 クライアント証明書を要求する MongoDB インスタンスへの接続

<?php$SSL_DIR  = "/vagrant/certs";$SSL_FILE = "CA_Root_Certificate.pem";$MYCERT   = "/vagrant/certs/ca-signed-client.pem";$ctx = stream_context_create(array(    "ssl" => array(        "local_cert"        => $MYCERT,        /* If the certificate we are providing was passphrase encoded, we need to set it here */        "passphrase"        => "My Passphrase for the local_cert",        /* Optionally verify the server is who he says he is */        "cafile"            => $SSL_DIR . "/" . $SSL_FILE,        "allow_self_signed" => false,        "verify_peer"       => true,        "verify_peer_name"  => true,        "verify_expiry"     => true,    ),));$mc = new MongoClient(    "mongodb://server1/?ssl=true",     array(),     array("context" => $ctx));?>

例4 X.509 証明書による認証

ユーザー名は、X509 の certificate subject から次のように取得できます。


openssl x509 -in /vagrant/certs/ca-signed-client.pem -inform PEM -subject -nameopt RFC2253

<?php$ctx = stream_context_create( array(    "ssl" => array(        "local_cert" => "/vagrant/certs/ca-signed-client.pem",    )) );$mc = new MongoClient(    'mongodb://username@server1/?authSource=$external&authMechanism=MONGODB-X509&ssl=true',     array(),     array("context" => $ctx));?>

ここで、username は certificate subject となります。


変更履歴

バージョン 説明
1.5.0 X509 認証のサポートが追加されました。
1.4.0 SSL を使って MongoDB に接続できるようになりました。