- mongo5.0.5
用户是跟着库创建的,在哪个库创建的什么权限的什么用户,只对此库有相应权限(除超级管理员以外)
1.开启认证
配置认证文件
vi /etc/mongod.conf
vi /etc/mongod.conf
- 开启认证
security:
authorization: enabled
security:
authorization: enabled
非yaml格式
auth=true
auth=true
- 关闭认证
//注释这两句 => 关闭认证
#security:
# authorization: enabled
//注释这两句 => 关闭认证
#security:
# authorization: enabled
- 重启
systemctl restart mongod
systemctl restart mongod
配置admin密码
use admin
db.createUser(
{
user: "admin",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
use admin
db.createUser(
{
user: "admin",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
- 通过外部脚本执行
sql
mongosh db_name --eval "db.createUser({user:'username',pwd:'123456qwe',roles:[{role:'userAdminAnyDatabase',db:'admin'}]})" --port 27018
mongosh db_name --eval "db.createUser({user:'username',pwd:'123456qwe',roles:[{role:'userAdminAnyDatabase',db:'admin'}]})" --port 27018
登陆
[root@slave01 ~]# mongosh -u mongouser -p --authenticationDatabase admin
MongoDB shell version v5.0.5
Enter password:
#或者登陆之后认证
> use admin
switched to db admin
> db.auth("username","password");
1
#返回1,代表正常
[root@slave01 ~]# mongosh -u mongouser -p --authenticationDatabase admin
MongoDB shell version v5.0.5
Enter password:
#或者登陆之后认证
> use admin
switched to db admin
> db.auth("username","password");
1
#返回1,代表正常
2.创建普通用户
管理员通常没有数据库的读写权限,只有操作用户的权限, 因此我们只需要赋予管理员userAdminAnyDatabase角色即可。
另外管理员账户必须在admin数据库下创建,3.0版本后没有admin数据库,但我们可以手动use一个。注:use命令在切换数据库时,如果切换到一个不存在的数据库,MongodDB会自动创建该数据库
use test
db.createUser(
{
user: 'yiduuser',
pwd: 'fa2e5474db854dd',
roles: [ { role: 'readWrite', db: 'EiduApp' } ]
}
);
#或者
db.createUser({user: "user", pwd:"user", roles: [ { role: "readWrite", db: "db_name" } ]})
use test
db.createUser(
{
user: 'yiduuser',
pwd: 'fa2e5474db854dd',
roles: [ { role: 'readWrite', db: 'EiduApp' } ]
}
);
#或者
db.createUser({user: "user", pwd:"user", roles: [ { role: "readWrite", db: "db_name" } ]})
创建超级管理员
#创建前要use admin这个验证库,否则无法登陆
use admin
db.createUser({user: "root", pwd: "redhat", roles: [ { role: "root", db: "admin" } ]})
或
use admin
db.createUser(
{
user: "root",
pwd: "redhat",
roles: [ { role: "root", db: "admin" } ]
})
#查看超级用户信息前要进入admin库,系统把超级用户信息存放在admin库
use admin
db.system.users.find()
或
db.system.users.find().pretty()
#验证用户
#返回 1 为可用
db.auth('root','redhat')
#创建前要use admin这个验证库,否则无法登陆
use admin
db.createUser({user: "root", pwd: "redhat", roles: [ { role: "root", db: "admin" } ]})
或
use admin
db.createUser(
{
user: "root",
pwd: "redhat",
roles: [ { role: "root", db: "admin" } ]
})
#查看超级用户信息前要进入admin库,系统把超级用户信息存放在admin库
use admin
db.system.users.find()
或
db.system.users.find().pretty()
#验证用户
#返回 1 为可用
db.auth('root','redhat')
创建库管理员用户
#建议创建用户之前先use到准备创建的库操作用户(只能操作olda库)
use olda
db.createUser(
{
user: "yiduuser",
pwd: "fa2e5474db854dd",
roles: [ { role: "dbAdmin", db: "EiduApp" } ]
})
#建议创建用户之前先use到准备创建的库操作用户(只能操作olda库)
use olda
db.createUser(
{
user: "yiduuser",
pwd: "fa2e5474db854dd",
roles: [ { role: "dbAdmin", db: "EiduApp" } ]
})
- 创建管理多个库的用户
#duouser这个用户可以多olda库读写,对test库只能读
use olda
db.createUser(
{
user: 'duouser',
pwd: 'duouser',
roles: [
{ role: 'readWrite', db: 'olda' },
{ role: 'read', db: 'test' } ] } )
#连接
mongo -uduouser -pduouser 10.0.0.20/olda
#duouser这个用户可以多olda库读写,对test库只能读
use olda
db.createUser(
{
user: 'duouser',
pwd: 'duouser',
roles: [
{ role: 'readWrite', db: 'olda' },
{ role: 'read', db: 'test' } ] } )
#连接
mongo -uduouser -pduouser 10.0.0.20/olda
创建读账户
>use test;
>db.createUser({user:"reader",pwd:"reader",roles:[{role:"read",db:"test"}]})#创建test库只读用户
>use test;
>db.createUser({user:"reader",pwd:"reader",roles:[{role:"read",db:"test"}]})#创建test库只读用户
创建写账户
>use test;
>db.createUser({user:"writer",pwd:"writer",roles:[{role:"readWrite",db:"test"}]})#创建test库读写用
>use test;
>db.createUser({user:"writer",pwd:"writer",roles:[{role:"readWrite",db:"test"}]})#创建test库读写用
用户指定加密方式
db.createUser({
user: "yiduusers",
pwd: "fa2e5474db854dd",
roles: [ { role: "dbAdmin", db: "EiduApp" } ],
mechanisms : ["SCRAM-SHA-256"]
})
db.createUser({
user: "yiduusers",
pwd: "fa2e5474db854dd",
roles: [ { role: "dbAdmin", db: "EiduApp" } ],
mechanisms : ["SCRAM-SHA-256"]
})
完整用户案例
#程序中调用
在admin,和所在库中,都需要授权
use admin
db.createUser(
{
user: "leihuo",
pwd: "fa2e5474db854dd",
roles: [ { role: "dbOwner",db: "admin" } ]
}
)
use rank
db.createUser(
{
user: "leihuo",
pwd: "fa2e5474db854dd",
roles: [ { role: "dbOwner",db: "rank" } ]
}
)
####
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
#程序中调用
在admin,和所在库中,都需要授权
use admin
db.createUser(
{
user: "leihuo",
pwd: "fa2e5474db854dd",
roles: [ { role: "dbOwner",db: "admin" } ]
}
)
use rank
db.createUser(
{
user: "leihuo",
pwd: "fa2e5474db854dd",
roles: [ { role: "dbOwner",db: "rank" } ]
}
)
####
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
3.添加远程权限
#vim /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
bindIpAll: true
#vim /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
bindIpAll: true
- 重启服务
systemctl restart mongod.service
systemctl restart mongod.service
URI 形式的访问
生产中常用 URI 形式对数据库进行连接
javascript
mongodb://your.db.ip.address:27017/foo
mongodb://your.db.ip.address:27017/foo
添加用户名密码验证
javascript
mongodb://simpleUser:simplePass@your.db.ip.address:27017/foo
mongodb://simpleUser:simplePass@your.db.ip.address:27017/foo
4.用户管理和认证方法
官网文档:https://docs.mongodb.com/master/reference/security/#security-methods-in-the-mongo-shell
Name | Description |
---|---|
db.auth() | Authenticates a user to a database. |
db.changeUserPassword() | Changes an existing user's password. |
db.createUser() | Creates a new user. |
db.dropUser() | Removes a single user. |
db.dropAllUsers() | Deletes all users associated with a database. |
db.getUser() | Returns information about the specified user. |
db.getUsers() | Returns information about all users associated with a database. |
db.grantRolesToUser() | Grants a role and its privileges to a user. |
db.removeUser() | Deprecated. Removes a user from a database. |
db.revokeRolesFromUser() | Removes a role from a user. |
db.updateUser() | Updates user data. |
passwordPrompt() | Prompts for the password as an alternative to specifying passwords directly in various mongosh user authentication/management methods. |
- mongosh安装
https://downloads.mongodb.com/compass/mongosh-1.5.4-linux-x64.tgz
https://downloads.mongodb.com/compass/mongosh-1.5.4-linux-x64.tgz
5.用户角色
官方详细档:https://docs.mongodb.com/master/reference/security/#security-methods-in-the-mongo-shell
Name | Description |
---|---|
db.createRole() | Creates a role and specifies its privileges. |
db.dropRole() | Deletes a user-defined role. |
db.dropAllRoles() | Deletes all user-defined roles associated with a database. |
db.getRole() | Returns information for the specified role. |
db.getRoles() | Returns information for all the user-defined roles in a database. |
db.grantPrivilegesToRole() | Assigns privileges to a user-defined role. |
db.revokePrivilegesFromRole() | Removes the specified privileges from a user-defined role. |
db.grantRolesToRole() | Specifies roles from which a user-defined role inherits privileges. |
db.revokeRolesFromRole() | Removes inherited roles from a role. |
db.updateRole() | Updates a user-defined role. |
read | 允许用户读取指定数据库 |
---|---|
readWrite | 允许用户读写指定数据库 |
dbAdmin | 允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile |
dbOwner | 允许在当前DB中执行任意操作 |
userAdmin | 允许用户向system.users集合写入,可以在指定数据库里创建、删除和管理用户 |
clusterAdmin | 只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限 |
readAnyDatabase | 只在admin数据库中可用,赋予用户所有数据库的读权限 |
readWriteAnyDatabase | 只在admin数据库中可用,赋予用户所有数据库的读写权限 |
userAdminAnyDatabase | 只在admin数据库中可用,赋予用户所有数据库的userAdmin权限,除config和local |
dbAdminAnyDatabase | 只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限 |
root | 只在admin数据库中可用。超级账号,超级权限,包含所有权限 |
clusterAdmin | 只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限 |
clusterManager | |
clusterMonitor | |
hostManager | |
backup | 备份MongoDB数据最小的权限 |
restore | 从备份文件中还原恢复MongoDB数据(处理system.profile集合)的权限 |
查找用户
sql
#切换到admin
> use admin
switched to db admin
> db.system.users.find();
#或者格式化输出
>db.system.users.find().pretty()
#或者
>show users;
>db.getUsers();//查看所有用户
#或者
>db.runCommand({usersInfo:"username"})
#切换到admin
> use admin
switched to db admin
> db.system.users.find();
#或者格式化输出
>db.system.users.find().pretty()
#或者
>show users;
>db.getUsers();//查看所有用户
#或者
>db.runCommand({usersInfo:"username"})
创建管理员用户
sql
>use admin
>db.createUser({user:'bjsxt',pwd:'bjsxtpwd',roles:[{role:'userAdminAnyDatabase',db:'admin'}])
#查看用户
>show users
>use admin
>db.createUser({user:'bjsxt',pwd:'bjsxtpwd',roles:[{role:'userAdminAnyDatabase',db:'admin'}])
#查看用户
>show users
更新用户角色
语法:db.updateUser( "用户名","roles":[{"role":"角色名称"},{"更新项2":"更新内容"}])
>use admin
>db.system.users.find();
{ "_id" : "test.testuser", "userId" : UUID("334e360a-eedb-4b15-bf74-dbd0b471017a"), "user" : "testuser", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "GLiQHuCyw0arlAaU4im+Tw==", "storedKey" : "Kczjk8bCUkgTzAM7T8uWeSC/lZY=", "serverKey" : "TWx/lx5SaTO3eWtJv62KVSlKGvo=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "Htwx1Oe9fktN028lqayj3b+jxZ7AsTt9SzQ15A==", "storedKey" : "fNPhyvhxMs4VDvsXrabRDEOqRS9MmNXZZeFzri/rDYY=", "serverKey" : "FO7BUayfvl3ZqPYHpkTQHGgU1cST9VzUmubku6YQY34=" } }, "roles" : [ { "role" : "readWrite", "db" : "test" } ] }
#更新
>use test
>db.updateUser("testuser",{roles : [{"role" : "userAdminAnyDatabase","db" : "admin"},{"role" : "dbAdminAnyDatabase","db" : "admin"}]})
标注:如果没有提示任何信息则表示更新成功。退出当前客户端重新连接即可生效
语法:db.updateUser( "用户名","roles":[{"role":"角色名称"},{"更新项2":"更新内容"}])
>use admin
>db.system.users.find();
{ "_id" : "test.testuser", "userId" : UUID("334e360a-eedb-4b15-bf74-dbd0b471017a"), "user" : "testuser", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "GLiQHuCyw0arlAaU4im+Tw==", "storedKey" : "Kczjk8bCUkgTzAM7T8uWeSC/lZY=", "serverKey" : "TWx/lx5SaTO3eWtJv62KVSlKGvo=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "Htwx1Oe9fktN028lqayj3b+jxZ7AsTt9SzQ15A==", "storedKey" : "fNPhyvhxMs4VDvsXrabRDEOqRS9MmNXZZeFzri/rDYY=", "serverKey" : "FO7BUayfvl3ZqPYHpkTQHGgU1cST9VzUmubku6YQY34=" } }, "roles" : [ { "role" : "readWrite", "db" : "test" } ] }
#更新
>use test
>db.updateUser("testuser",{roles : [{"role" : "userAdminAnyDatabase","db" : "admin"},{"role" : "dbAdminAnyDatabase","db" : "admin"}]})
标注:如果没有提示任何信息则表示更新成功。退出当前客户端重新连接即可生效
- 查看当前用户信息
>use test;
> show users;
{
"_id" : "test.testuser",
"userId" : UUID("334e360a-eedb-4b15-bf74-dbd0b471017a"),
"user" : "testuser",
"db" : "test",
"roles" : [
{
"role" : "dbAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
#或者
>db.system.users.find();
>use test;
> show users;
{
"_id" : "test.testuser",
"userId" : UUID("334e360a-eedb-4b15-bf74-dbd0b471017a"),
"user" : "testuser",
"db" : "test",
"roles" : [
{
"role" : "dbAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
#或者
>db.system.users.find();
更新用户密码
更新用户密码有两种方式:
1)使用db.updateUser()函数更新密码。
2)使用db.changeUserPassword()函数更新密码
语法格式:db.updateUser("用户名",{"pwd":"新密码"})
> use test
switched to db test
> db.updateUser("testuser",{"pwd":"123456"})
语法格式:db.updateUser("用户名",{"pwd":"新密码"})
> use test
switched to db test
> db.updateUser("testuser",{"pwd":"123456"})
语法格式:db.changeUserPassword("用户名","新密码")
>use test;
>db.changeUserPassword("testuser","123")
语法格式:db.changeUserPassword("用户名","新密码")
>use test;
>db.changeUserPassword("testuser","123")
权限修改
注:updateuser它是完全替换之前的值,如果要新增或添加roles而不是代替它
> show users
{
"_id" : "test.testuser",
"userId" : UUID("1a81e6ae-e80e-48eb-a526-6596988518a7"),
"user" : "testuser",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.grantRolesToUser("testuser", [{role:"readWrite", db:"test"},{role:"read", db:"test"}])
> show users
{
"_id" : "test.testuser",
"userId" : UUID("1a81e6ae-e80e-48eb-a526-6596988518a7"),
"user" : "testuser",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> show users
{
"_id" : "test.testuser",
"userId" : UUID("1a81e6ae-e80e-48eb-a526-6596988518a7"),
"user" : "testuser",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.grantRolesToUser("testuser", [{role:"readWrite", db:"test"},{role:"read", db:"test"}])
> show users
{
"_id" : "test.testuser",
"userId" : UUID("1a81e6ae-e80e-48eb-a526-6596988518a7"),
"user" : "testuser",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
权限收回
sql
>use test
> show users
{
"_id" : "test.testuser",
"userId" : UUID("1a81e6ae-e80e-48eb-a526-6596988518a7"),
"user" : "testuser",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.revokeRolesFromUser("testuser",[{role:"read", db:"test"}])
>show users;
>use test
> show users
{
"_id" : "test.testuser",
"userId" : UUID("1a81e6ae-e80e-48eb-a526-6596988518a7"),
"user" : "testuser",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.revokeRolesFromUser("testuser",[{role:"read", db:"test"}])
>show users;
删除用户
通过db.dropUser()函数可删除指定用户。删除成功后会返回true。在删除用户时需要切换到创建时用户所指定的数据库中才可以删除
。
注意:需要使用具有userAdminAnyDatabse角色管理员用户才可以删除其他用户
> use test;
switched to db test
> db.dropUser("testuser");
true
标注:该函数返回了true,表示删除成功
> use test;
switched to db test
> db.dropUser("testuser");
true
标注:该函数返回了true,表示删除成功
官方文档:https://docs.mongodb.com/manual/reference/method/db.createUser/
案例:
db.createUser({
user:"user01",
pwd:"123456",
customData:{
name:'tom',
email:'ss@qq.com',
age:18,
},
roles:[
{role:"readWrite",db:"test"},
{role:"readWrite",db:"test"},
'read' //对其他数据库只有读权限,对test有读写
]
}
)
#修改含有描述信息的密码账户
db.runCommand(
{
updateUser:"username",
pwd:"123456",
customData:{
name:'tom',
email:'ss@qq.com',
age:18,
}
}
)
db.createUser({
user:"user01",
pwd:"123456",
customData:{
name:'tom',
email:'ss@qq.com',
age:18,
},
roles:[
{role:"readWrite",db:"test"},
{role:"readWrite",db:"test"},
'read' //对其他数据库只有读权限,对test有读写
]
}
)
#修改含有描述信息的密码账户
db.runCommand(
{
updateUser:"username",
pwd:"123456",
customData:{
name:'tom',
email:'ss@qq.com',
age:18,
}
}
)
net方式连接
mongodb://leihuo:fa2e5474db854dd@172.16.195.193:47017/EiduApp?authSource=EiduApp&authMechanism=SCRAM-SHA-1
mongodb://leihuo:fa2e5474db854dd@172.16.195.193:47017/EiduApp?authSource=EiduApp&authMechanism=SCRAM-SHA-1
6.集群角色
#让这名用户能够访问系统中的所有数据库、创建新的数据库以及管理 MongoDB 集群和副本集
> use admin
switched to db admin
> db.createUser(
{
user: "dbadmin",
pwd: "abc123",
roles: [ "readWriteAnyDatabase", "dbAdminAnyDatabase","clusterAdmin" ]
}
)
#让这名用户能够访问系统中的所有数据库、创建新的数据库以及管理 MongoDB 集群和副本集
> use admin
switched to db admin
> db.createUser(
{
user: "dbadmin",
pwd: "abc123",
roles: [ "readWriteAnyDatabase", "dbAdminAnyDatabase","clusterAdmin" ]
}
)