首页 > 解决方案 > MongoDB + Rails 错误:命令查找需要身份验证

问题描述

我无法在从 Rails 6 应用程序启用访问控制的 MongoDB 上运行命令。

这是我得到的错误:

Mongo::Error::OperationFailure (command find requires authentication (13) (on localhost:27017, modern retry, attempt 1))

这是我的mongoid.yml

staging:
  clients:
    default:
      database: mydb_staging
      hosts:
        - localhost:27017
      user: 'julien'
      password: 'mypass'
      auth_source: admin
      auth_mech: :scram
      options:

我可以从命令行在 mongo 中连接和验证,我可以连接到它并通过 Robomongo 远程验证。

这是我创建的用户:

> use admin
switched to db admin
> db.auth('julien', 'mypass')
1
> db.getUsers()
[
    {
        "_id" : "admin.julien",
        "userId" : UUID("3444564f-7dcd-4283-8fb1-ce4f122ed9b8"),
        "user" : "julien",
        "db" : "admin",
        "roles" : [
            {
                "role" : "userAdminAnyDatabase",
                "db" : "admin"
            },
            {
                "role" : "root",
                "db" : "admin"
            },
            {
                "role" : "readWriteAnyDatabase",
                "db" : "admin"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]

我什至在 Rails 应用程序的特定数据库中创建了一个具有相同凭据的用户:

> use mydb_staging
switched to db mydb_staging
> db.getUsers()
[
    {
        "_id" : "mydb_staging.julien",
        "userId" : UUID("dc2d8ab6-4f01-4568-be9d-6486283aea14"),
        "user" : "julien",
        "db" : "mydb_staging",
        "roles" : [
            {
                "role" : "readWrite",
                "db" : "mydb_staging"
            }
        ],
        "mechanisms" : [
            "SCRAM-SHA-1",
            "SCRAM-SHA-256"
        ]
    }
]

更多细节:

$ mongo --version
MongoDB shell version v4.2.8
git version: 43d25964249164d76d5e04dd6cf38f6111e21f5f
OpenSSL version: OpenSSL 1.1.1  11 Sep 2018
allocator: tcmalloc
modules: none
build environment:
    distmod: ubuntu1804
    distarch: x86_64
    target_arch: x86_64

宝石版本:

为什么我不能通过 Rails 运行命令,我该如何解决这个问题?

编辑

这是来自 rails 控制台的示例:

$ RAILS_ENV=staging bundle exec rails console
Loading staging environment (Rails 6.0.3.2)
irb(main):001:0> User.count
Traceback (most recent call last):
        1: from (irb):1
Mongo::Error::OperationFailure (command count requires authentication (13) (on localhost:27017, modern retry, attempt 1))

标签: ruby-on-railsmongodbmongoid

解决方案


Nek的评论为我指明了正确的方向,如果您查看该文件的文档mongoid.yml,您会注意到有两个 options部分,我不得不将身份验证部分移到其中一个部分中,正确的配置如下所示:

staging:
  clients:
    default:
      database: mydb_staging
      hosts:
        - localhost:27017
      options:
        user: 'julien'
        password: 'mypass'
        auth_source: admin
        auth_mech: :scram

推荐阅读