首先确保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
权限控制的核心是启用身份验证,需修改MongoDB配置文件(通常位于/etc/mongod.conf
):
sudo nano /etc/mongod.conf
找到security
section,添加或修改以下内容:
security:
authorization: enabled
保存文件后,重启MongoDB服务使配置生效:
sudo systemctl restart mongod
为便于后续管理,建议先创建一个管理员用户(拥有root
角色,可管理所有数据库和用户):
# 连接到MongoDB shell
mongo
# 切换到admin数据库
use admin
# 创建管理员用户(用户名:admin,密码:your_admin_password)
db.createUser({
user: "admin",
pwd: "your_admin_password",
roles: ["root"]
})
# 退出shell
exit
根据需求为特定数据库创建用户,并分配相应角色(以下为常见角色示例):
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
使用创建的用户连接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
/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的权限设置,确保数据库访问的安全性和可控性。