温馨提示×

MongoDB在Linux上的权限设置如何操作

小樊
42
2025-10-12 03:31:13
栏目: 云计算

MongoDB在Linux上的权限设置操作步骤

1. 安装MongoDB(若未安装)

首先确保Linux系统已安装MongoDB Community Server。可通过MongoDB官方网站下载对应发行版的安装包,或使用包管理器安装(如Ubuntu使用apt,CentOS使用yum)。安装完成后,启动MongoDB服务并设置为开机自启:

# Ubuntu/Debian示例
sudo apt update && sudo apt install -y mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod

2. 启用MongoDB身份验证

权限控制的核心是启用身份验证,需修改MongoDB配置文件(通常位于/etc/mongod.conf):

sudo nano /etc/mongod.conf

找到security section,添加或修改以下内容:

security:
  authorization: enabled

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

sudo systemctl restart mongod

3. 创建管理员用户(可选但推荐)

为便于后续管理,建议先创建一个管理员用户(拥有root角色,可管理所有数据库和用户):

# 连接到MongoDB shell
mongo
# 切换到admin数据库
use admin
# 创建管理员用户(用户名:admin,密码:your_admin_password)
db.createUser({
  user: "admin",
  pwd: "your_admin_password",
  roles: ["root"]
})
# 退出shell
exit

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

根据需求为特定数据库创建用户,并分配相应角色(以下为常见角色示例):

  • 只读权限(仅能查询数据):
    mongo -u admin -p your_admin_password --authenticationDatabase admin
    use myDatabase  # 切换到目标数据库
    db.createUser({
      user: "readOnlyUser",
      pwd: "readOnlyUser_password",
      roles: [{ role: "read", db: "myDatabase" }]
    })
    exit
    
  • 读写权限(能查询和修改数据):
    mongo -u admin -p your_admin_password --authenticationDatabase admin
    use myDatabase
    db.createUser({
      user: "readWriteUser",
      pwd: "readWriteUser_password",
      roles: [{ role: "readWrite", db: "myDatabase" }]
    })
    exit
    
  • 自定义角色(如仅能创建集合):
    mongo -u admin -p your_admin_password --authenticationDatabase admin
    use admin
    db.createRole({
      role: "createCollectionRole",
      privileges: [{
        resource: { db: "myDatabase", collection: "" },
        actions: ["createCollection"]
      }],
      roles: []
    })
    db.createUser({
      user: "customUser",
      pwd: "customUser_password",
      roles: ["createCollectionRole"]
    })
    exit
    

5. 验证用户权限

使用创建的用户连接MongoDB,测试其权限是否生效:

# 只读用户验证
mongo -u readOnlyUser -p readOnlyUser_password --authenticationDatabase myDatabase
use myDatabase
db.mycollection.find()  # 应能正常查询
db.mycollection.insert({ name: "test" })  # 应报错(无写入权限)
exit

# 读写用户验证
mongo -u readWriteUser -p readWriteUser_password --authenticationDatabase myDatabase
use myDatabase
db.mycollection.insert({ name: "test" })  # 应能正常插入
db.mycollection.find()  # 应能正常查询
exit

6. 可选:增强安全性配置

  • 启用TLS/SSL加密:编辑/etc/mongod.conf,添加SSL配置(需提前生成证书):
    net:
      ssl:
        mode: requireSSL
        PEMKeyFile: /path/to/mongodb.pem
        CAFile: /path/to/ca.pem
    
    重启服务后,客户端连接需指定证书:
    mongo --ssl --sslCAFile /path/to/ca.pem --sslPEMKeyFile /path/to/mongodb.pem -u readWriteUser -p readWriteUser_password --authenticationDatabase myDatabase
    
  • 使用防火墙限制访问:通过ufw限制MongoDB端口(默认27017)的访问:
    sudo ufw allow from 192.168.1.0/24 to any port 27017  # 仅允许指定IP段访问
    sudo ufw enable
    

通过以上步骤,即可在Linux系统上完成MongoDB的权限设置,确保数据库访问的安全性和可控性。

0