【问题标题】:Mongoose connection authentication failedMongoose 连接认证失败
【发布时间】:2018-01-16 11:58:00
【问题描述】:

在这个帮助下,我在 mongo shell 中创建了一个超级用户:Create Superuser in mongo

user: "try1"
passw: "hello"

在 mongo cmd 中,我有 3 个数据库:'admin'、'myDatabase' 和 'local'。

现在我尝试使用此授权连接到名为“myDatabase”的数据库。

mongoose.connect('mongodb://try1:hello@localhost:27017/myDatabase');

但这是我得到的错误:

名称:'MongoError',
消息:'身份验证失败。',
好的:0,
errmsg: '身份验证失败。',
代码:18,
代号:'AuthenticationFailed' }
猫鼬断开连接
Mongoose 通过 ${msg}

断开连接

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    如果您的authSource 是数据库(在示例中为“myDB”)本身,并且您尝试使用ConnectionOption dbName,则必须匹配authSource

    await mongoose.connect('mongodb://localhost:27017,' {
      dbName: 'myDB',
      user: 'myUser',
      pass: 'asldjaskdj'
    );
    

    将因错误而失败:

    {
        "msg": "Authentication failed",
        "attr": {
            "mechanism": "SCRAM-SHA-1",
            "principalName": "myUser",
            "authenticationDatabase": "admin",
            "client": "...",
            "result": "UserNotFound: Could not find user \"myUser\" for db \"admin\""
        }
    }
    

    authSource: 'myDB' 添加到连接选项将起作用。示例:

    await mongoose.connect('mongodb://localhost:27017,' {
      dbName: 'myDB',
      authSource: 'myDB',
      user: 'myUser',
      pass: 'asldjaskdj'
    );
    

    【讨论】:

      【解决方案2】:

      这是现在的正确答案。其他的并不完全正确。

      await mongoose.connect("mongodb://localhost:27017/db", {
      poolSize: 10,
      authSource: "admin",
      user: "admin",
      pass: "password",
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
      useFindAndModify: false, });
      

      【讨论】:

        【解决方案3】:

        Sintaxis:

        mongoose.connect('mongodb://username:password@host:port/database?authSource=admin'); 
        
        Example:
        mongoose.connect('mongodb://myUser:myPassword@localhost:27017/myDataBase?authSource=admin');
        

        【讨论】:

          【解决方案4】:

          当我使用上述答案时,我得到了MongoParseError: credentials must be an object with 'username' and 'password' properties
          将用户名密码添加到身份验证对象解决了问题

            try {
              await connect("mongodb://localhost:27017/dbname", {
                auth: { username: "root", password: "example" },
                authSource: "admin",
              });
              console.log("Connected to mongo db");
            } catch (error) {
              console.error("Error connecting to mongodb", error);
            }
          

          mongodb 5.0.2版
          猫鼬 6.0.4

          【讨论】:

            【解决方案5】:

            我遇到了同样的问题。我正在使用较旧的 MongoDB 实例。我只是在连接字符串中添加了authSource=admin,它解决了问题。

            【讨论】:

              【解决方案6】:

              几个小时前我也遇到过同样的问题,但我终于解决了。我的代码是:

              mongoose.createConnection(
                "mongodb://localhost:27017/dbName",
                {
                  "auth": {
                    "authSource": "admin"
                  },
                  "user": "admin",
                  "pass": "password"
                }
              );
              

              【讨论】:

              • 为什么mongoose文档这么难!?我已经尝试了很多这些变体,但只是没有尝试过这个。终于你拯救了我的一天。谢谢@kartGIS
              • 你用的是什么猫鼬版本?
              • 感谢您的精彩提示! @Carlos.V 我在 node: 14.6.0 上使用 "mongoose": "^5.9.24"
              【解决方案7】:

              在 Mongodb 4.2 和 Mongoose 5.7.13 上工作正常

              Node.js

              const Connect = async () => {
              
                  let url = "mongodb://localhost:27017/test_db";
              
                  try {
              
                      let client = await Mongoose.connect( url, {
                          poolSize: 10,
                          authSource: "admin",
                          user: "root",
                          pass: "root123", 
                          useCreateIndex: true,
                          useNewUrlParser: true,
                          useUnifiedTopology: true
                      } );
              
                      log( "Database is connected!" );
                  } catch ( error ) {
                      log( error.stack );
                      process.exit( 1 );
                  }
              
              }
              Connect();
              

              /etc/mongod.conf

              systemLog:
                destination: file
                logAppend: true
                path: /var/log/mongodb/mongod.log
              
              storage:
                dbPath: /var/lib/mongo
                journal:
                  enabled: true
              
              processManagement:
                fork: true  # fork and run in background
                pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
                timeZoneInfo: /usr/share/zoneinfo
              
              net:
                port: 27017
                bindIp: 0.0.0.0 
              
              setParameter:
                 enableLocalhostAuthBypass: false
              
              security:
                authorization: enabled
              

              数据库用户

              use admin;
              db.createUser(
                {
                  user: "root",
                  pwd: "root123",
                  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
                }
              )
              
              show users;
              {
                 _id": "admin.root",
                 "userId": UUID( "5db3aafd-b1fd-4bea-925e-8a4bfb709f22" ),
                 "user": "root",
                 "db": "admin",
                 "roles": [ {
                      "role": "userAdminAnyDatabase",
                      "db": "admin"
                    },
                    {
                      "role": "readWriteAnyDatabase",
                      "db": "admin"
                    }
                 ],
                 "mechanisms": [
                     "SCRAM-SHA-1",
                     "SCRAM-SHA-256"
                 ]
              }
              

              【讨论】:

              • 对我来说,只需添加 userpassauthSource: "admin" 就可以了。非常感谢。
              【解决方案8】:

              我有同样的问题,通过删除 'authSource' 参数解决了

              /* Not working */
              mongoose.connect("mongodb://localhost:27017/test", {
                  "auth": { "authSource": "admin" },
                  "user": "admin",
                  "pass": "admin123",
                  "useMongoClient": true
              });
              
              /* Working */
              mongoose.connect("mongodb://localhost:27017/test", {
                  "user": "admin",
                  "pass": "admin123",
                  "useMongoClient": true
              });
              

              在 Mongoose-v5.0.0 上测试。

              【讨论】:

                【解决方案9】:

                除了@kartGIS,我还添加了一个选项以使连接代码尽可能完美。

                mongoose.connect("mongodb://localhost:27017/databaseName", {
                    "auth": { "authSource": "admin" },
                    "user": "username",
                    "pass": "password",
                    "useMongoClient": true
                });
                

                【讨论】:

                • 你能解释一下这个选项是什么 "auth": { "authSource": "admin" },?
                • "auth": { "authSource": "admin" } 表示将authenticationDatabase 设置为admin
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2022-12-01
                • 2021-04-27
                • 2013-10-09
                • 2017-11-08
                • 2015-07-09
                相关资源
                最近更新 更多