PHP5 mongodb 切换db报错 Authentication failed on database admin

权限
已经开启,在test上创建了用户test1,并赋予了 test的readWrite 和 reporting的read权限。

{
    "_id" : "test.test1",
    "userId" : UUID("406cb77c-1fc0-4f34-a257-1c975349552a"),
    "user" : "test1",
    "db" : "test",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        },
        {
            "role" : "read",
            "db" : "reporting"
        }
    ],
    "mechanisms" : [
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
    ]
}

使用CLI模式进行连接,mongo -u test1 -p --authenticationDatabase test 可以进入,show dbs会显示两个库。

D:\>mongo -u test1 -p --authenticationDatabase test
MongoDB shell version v4.0.10
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=test&gssapiServiceName=mong
odb
Implicit session: session { "id" : UUID("b0e13217-63b3-454b-b8fc-32dd24fbfd1d")
}
MongoDB server version: 4.0.10
> show dbs
reporting  0.000GB
test       0.000GB
> use reporting
switched to db reporting
> show collections
foo2
>

问题
但使用PHP连接mongodb,却只能在test库上操作,无法连接到 reporting 库。可在cli模式是可以。

$config = [
    'username' => 'test1',
    'password' => 'test1',
    'auth_db' => 'test',
    'host' => '127.0.0.1',
    'port' => '27017',
    'db' => 'reporting',
    'table' => 'foo2',
];

try {
    $conn = new MongoClient("mongodb://" . $config['username'] . ':' . $config['password'] . '@' . $config['host'] . ':' . $config['port'] . '/' . $config['auth_db']);
//        $conn = new MongoClient("mongodb://" . $config['host'], array(
//            'username' => $config['username'],
//            'password' => $config['password'],
//            'db' => $config['auth_db']
//        ));


    $dbs = $conn->selectDB($config['db']);
    $mongo = $dbs->selectCollection($config['table']);
    $row = $mongo->findOne();
} catch (Exception $e) {
    var_dump($e->getMessage());
}

报错内容

string(113) "Failed to connect to: 127.0.0.1:27017: SASL Authentication failed o
n database 'reporting': Authentication failed."

可问题是 test1用户对 reporting也有read权限啊,而且在 cli模式是完全可以列出和操作。

阅读 2.9k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进