debian

MongoDB在Debian上的权限配置指南

小樊
39
2025-10-17 04:40:49
栏目: 云计算

MongoDB在Debian上的权限配置指南

1. 安装MongoDB

首先确保Debian系统已更新,然后通过官方仓库安装MongoDB(以Debian 11 Bullseye为例):

sudo apt update && sudo apt upgrade -y
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
echo "deb [arch=amd64,arm64] https://repo.mongodb.org/apt/debian bullseye/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
sudo apt update
sudo apt install -y mongodb-org

启动MongoDB服务并设置开机自启:

sudo systemctl start mongod
sudo systemctl enable mongod

2. 启用身份验证

编辑MongoDB配置文件/etc/mongod.conf,在security部分添加或修改以下内容以启用认证:

security:
  authorization: enabled

保存文件后重启MongoDB服务使配置生效:

sudo systemctl restart mongod

3. 创建管理员用户

连接MongoDB shell(默认本地连接无需密码):

mongo

切换到admin数据库(管理员用户需在admin库中创建),创建具有root角色的管理员用户(root角色拥有所有权限):

use admin
db.createUser({
  user: "admin",
  pwd: "yourStrongPassword", // 替换为强密码
  roles: [{ role: "root", db: "admin" }]
})

退出shell:

exit

4. 创建数据库用户并分配权限

4.1 选择目标数据库

假设要为用户appUser创建myApp数据库的读写权限:

mongo -u admin -p yourStrongPassword --authenticationDatabase admin
use myApp

4.2 创建用户并分配角色

根据需求选择合适的内置角色(常见角色说明见下文),例如创建读写权限用户:

db.createUser({
  user: "appUser",
  pwd: "appUserPassword",
  roles: [{ role: "readWrite", db: "myApp" }] // 读写权限
})

或创建仅读权限用户:

db.createUser({
  user: "readOnlyUser",
  pwd: "readOnlyPassword",
  roles: [{ role: "read", db: "myApp" }] // 只读权限
})

内置角色说明

5. 验证用户权限

5.1 使用管理员登录

mongo -u admin -p yourStrongPassword --authenticationDatabase admin

5.2 切换到目标数据库并验证用户

use myApp
db.auth("appUser", "appUserPassword") // 返回1表示验证成功

5.3 测试权限操作

尝试插入数据(验证readWrite权限):

db.myCollection.insertOne({ name: "test" }) // 成功则权限正确

若权限不足,会返回Unauthorized错误。

6. 可选:配置IP白名单(增强安全性)

编辑/etc/mongod.conf,在net部分添加bindIpipWhitelist限制访问IP:

net:
  bindIp: 127.0.0.1,192.168.1.100  # 允许本地和指定IP访问
  # security:
  #   ipWhitelist: ["127.0.0.1", "192.168.1.100"] # MongoDB 6.0+版本使用此配置

保存后重启MongoDB服务:

sudo systemctl restart mongod

注意事项

0
看了该问题的人还看了