首页 > 解决方案 > 无法在 db.createUser() 中使用身份验证机制

问题描述

我正在使用 MongoDB 4.2。我试图测试如何使用 mongodb 中的所有身份验证机制。我做了这样的事情

db.createUser({user:"admin2", pwd: "admin2", roles : [{role:"readWrite", db: "test"}], mechanisms : ["SCRAM-SHA-256"]})

这适用于 SCRAM-SHA-1 和 SCRAM-SHA-256。但我尝试使用 PLAIN、GSSAPI、MONGODB-X509、MONGODB-CR。像这样,

db.createUser({user:"admin2", pwd: "admin2", roles : [{role:"readWrite", db: "test"}], mechanisms : ["PLAIN"]})

和其他人。但这不起作用抛出错误

uncaught exception: Error: couldn't add user: Unknown auth mechanism 'PLAIN'

这个问题的原因是什么?如何解决这个问题?

标签: mongodb

解决方案


如文档中所述,只有 scram 机制在 createUser 中有效。

$external对于其他机制,您需要在专用数据库中创建用户。是对 X.509 执行此操作的示例调用。

db.getSiblingDB("$external").runCommand(
  {
    createUser: "C=US,ST=New York,L=New York City,O=MongoDB,OU=x509,CN=localhost",
    roles: [
         { role: "root", db: "admin" },
    ],
    writeConcern: { w: "majority" , wtimeout: 5000 },
  }
)

推荐阅读