创建用户
格式
> db.createUser(
{
user:"<name>",
pwd:"<password>",
customData:{<any information>,roles:[{role:"<role>",db:"<database>"}]}
)
- roles 是指这个用户的类型/角色
- role:内建类型(read,readWrite,dbAdmin,dbOwner,userAdmin)
- db:是这个用户是创建在哪个数据库上
其他角色
- 数据库用户角色
read、readWrite;
- 数据库管理角色
dbAdmin、dbOwner、userAdmin;
- 集群管理角色
clusterAdmin、clusterManager、clusterMonitor、hostManager;
- 备份恢复角色
backup、restore;
- 所有数据库角色
readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
- 超级用户角色:root
这里还有几个角色间接或直接提供了系统超级用户的访问
(dbOwner 、userAdmin、userAdminAnyDatabase)
- 内部角色:__system
开启认证
查看数据库版本
# mongo
MongoDB shell version v3.4.7
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.7
> use admin
switched to db admin
> db.system.version.find()
{ "_id" : "featureCompatibilityVersion", "version" : "3.4" }
{ "_id" : "authSchema", "currentVersion" : 5 }
- 如果是如上结果,因为数据库版本不一致,远程连接时会出现Authorization failed错误。
解决方法:
> db.system.version.update({"_id":"authSchema"},{$set:{"currentVersion":3}})
- 如果是如下结果,则添加一条记录:
# mongo
MongoDB shell version v3.4.7
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.7
> use admin
switched to db admin
> db.system.version.find()
{ "_id" : "featureCompatibilityVersion", "version" : "3.4" }
> db.system.version.insert({"_id":"authSchema","currentVersion":3})
WriteResult({ "nInserted" : 1 })
> db.system.version.find()
{ "_id" : "featureCompatibilityVersion", "version" : "3.4" }
{ "_id" : "authSchema", "currentVersion" : 3 }
添加用户
> db.createUser({user:"admin",pwd:"123456",roles:[{"role":"userAdminAnyDatabase","db":"admin"},{"role":"readWrite","db":"test"}]})
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "readWrite",
"db" : "test"
}
]
}
修改配置文件
# bindIp: 127.0.0.1 那一行可以注释掉,也可以修改为如下所示:
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0 # Listen to local interface only, comment to listen on all interfaces.
# 远程连接数据库验证,旧版本为auth = true
security:
authorization: enabled
开放27017端口
systemctl restart mongod
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 27017 -j ACCEPT
测试连接
命令行模式
D:\Dev\Cmder
λ mongo 192.168.56.102:27017/admin -u whoami -p
MongoDB shell version v3.6.2
Enter password:
connecting to: mongodb://192.168.56.102:27017/admin
MongoDB server version: 3.4.10
>
MongoDB Compass
- 认证信息
- 连接成功