PHP Velho Oeste 2024

認証

MongoDB を --auth あるいは --keyFile オプションつきで起動すると、 まずログインしないとドライバを使った操作ができなくなります。 接続時の認証をするには、ユーザー名とパスワードを接続 URI に指定するか、あるいは MongoClient::__construct() でオプション "username" および "password" を指定します。

例1 "admin" データベースに対する認証

<?php
// ユーザー名とパスワードを接続 URI で指定する方法 (推奨)
$m = new MongoClient("mongodb://${username}:${password}@localhost");

// ユーザー名とパスワードをオプションの配列で指定する方法 (別の方法)
$m = new MongoClient("mongodb://localhost", array("username" => $username"password" => $password));
?>

デフォルトでは、ドライバは admin データベースに対する認証を試みます。別のデータベースに対する認証をするには、 データベースを接続 URI に指定するか、あるいは MongoClient::__construct() でオプション "db" を指定します。

例2 通常のデータベースに対する認証

<?php
// 認証データベースを接続 URI で指定する方法 (推奨)
$m = new MongoClient("mongodb://${username}:${password}@localhost/myDatabase");

// 認証データベースをオプションの配列で指定する方法 (別の方法)
$m = new MongoClient("mongodb://${username}:${password}@localhost", array("db" => "myDatabase"));
?>

接続が落ちると、ドライバが自動的に再接続と再認証を試みます。

add a note add a note

User Contributed Notes 2 notes

up
1
davida at quickplay dot com
9 years ago
How does this work for connections to replication sets?

Does the connection string become:
"mongodb://user:password@server1:27017,server2:27017,server3:27017"
up
0
dan at kayakaddict dot co dot uk
8 years ago
For connecting to a replica set with authentication it is possible to use a connection string like the following (substitute the port numbers, replica set name and DB with your own)

$m = new MongoClient("mongodb://${username}:${password}@localhost:27037,mongodb://${username}:${password}@localhost:27038",
array("replicaSet" => "test"_replica, "db" => "mytestdb"));

The second member string "mongodb://${username}:${password}@localhost:27038" does not need the username and password - however, if the connection to the first member fails I have not tested to see if the username and password persist to the second member.
To Top