认证

如果 MongoDB 服务器启动时使用了 --auth--keyFile 参数,你就必须在进行任何操作前进行认证。 你可以在连接时进行认证。方法是在链接字符串中指定用户名密码,或者在 MongoClient::__construct() 构造函数中指定 "username""password"

Example #1 针对“admin”数据库的认证

<?php
// Specifying the username and password in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost");

// Specifying the username and password via the options array (alternative)
$m = new MongoClient("mongodb://localhost", array("username" => $username"password" => $password));
?>

默认状态下,驱动会针对 admin 数据库进行认证。认证也可以对其他数据库进行。方法是在连接字符串中指定数据库名,或者 MongoClient::__construct() 构造函数中指定 "db"

Example #2 针对一般数据库的认证

<?php
// Specifying the authentication database in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost/myDatabase");

// Specifying the authentication database via the options array (alternative)
$m = new MongoClient("mongodb://${username}:${password}@localhost", array("db" => "myDatabase"));
?>

如果链接中断,驱动会重新尝试链接并会自动重新认证。

add a note add a note

User Contributed Notes 2 notes

up
1
dan at kayakaddict dot co dot uk
2 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.
up
1
davida at quickplay dot com
3 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"
To Top