Rails集成MongoDB Atlas遭遇授权失败问题及解决方案
Rails + MongoDB Atlas 授权错误(Mongo::Error::OperationFailure)解决方法
问题现象
在Rails项目中集成MongoDB Atlas时,无论是通过控制器创建/读取数据,还是在控制台手动保存模型,都会触发Mongo::Error::OperationFailure授权错误,核心提示为not authorized on admin to execute command。
控制器报错信息
# Mongo::Error::OperationFailure in PostsController#create [8000:AtlasError]: (Unauthorized) not authorized on admin to execute command { insert: "posts", $db: "admin", ordered: true, writeConcern: { w: "majority" }, txnNumber: 1.000000, lsid: { id: {4 [129 103 129 204 83 248 73 51 140 2 11 71 126 35 223 247]} } } (on ac-xjgsx9t-shard-00-02.whzyr5q.mongodb.net:27017, modern retry, attempt 1)
控制台手动保存报错信息
3.0.0 :003 > post = Post.new(title: "Please", body: "Help me stack overflow") => #<Post _id: 63f590426e92a40ae84042bb, created_at: nil, updated_at: nil, title: "Please", body: "Help me stack overf... 3.0.0 :004 > post.save /Users/myuser/.rvm/gems/ruby-3.0.0/gems/mongo-2.18.2/lib/mongo/operation/result.rb:364:in `raise_operation_failure': [8000:AtlasError]: (Unauthorized) not authorized on admin to execute command { insert: "posts", $db: "admin", ordered: true, writeConcern: { w: "majority" }, txnNumber: 1.000000, lsid: { id: {4 [235 127 224 68 69 252 76 207 177 72 92 1 135 84 190 63]} } } (on ac-xjgsx9t-shard-00-02.whzyr5q.mongodb.net:27017, modern retry, attempt 1) (Mongo::Error::OperationFailure)
原有配置(mongoid.yml)
development: clients: default: uri: mongodb+srv://hiddenuser:hiddenpassword@cluster0.whzyr5q.mongodb.net/?retryWrites=true&w=majority options: server_selection_timeout: 5
已尝试的无效方案
- 更换MongoDB Ruby驱动旧版本
- 配置集群IP白名单
- 为数据库用户赋予全权限
- 添加
atlasAdmin权限用户
注:输入错误密码会触发认证失败,说明账号密码本身有效。
解决方法
问题根源在于连接URI未指定目标数据库,导致程序默认连接admin库,但当前用户无admin库的操作权限。
修正连接URI,在?retryWrites前添加你的目标数据库名称即可:
# 修正后的mongoid.yml配置 development: clients: default: uri: mongodb+srv://hiddenuser:hiddenpassword@cluster0.whzyr5q.mongodb.net/你的数据库名称?retryWrites=true&w=majority options: server_selection_timeout: 5
内容的提问来源于stack exchange,提问作者Gusteau
相关产品推荐
相关产品推荐

