MongoDB用户管理
1:注意
MongoDB 数据库默认是没有用户名及密码的,即无权限访问限制。为了方便数据库的管理和安全,需创建数据库用户
2:用户的权限
用户中权限的说明
权限 说明
Read 允许用户读取指定数据库
readWrite 允许用户读写指定数据库
dbAdmin 允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问 system.profile
userAdmin 允许用户向 system.users 集合写入,可以找指定数据库里创建、删除和管理用户
clusterAdmin 只在 admin 数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
readAnyDatabase 只在 admin 数据库中可用,赋予用户所有数据库的读权限
readWriteAnyDatabase 只在 admin 数据库中可用,赋予用户所有数据库的读写权限
userAdminAnyDatabase 只在 admin 数据库中可用,赋予用户所有数据库的 userAdmin 权限
dbAdminAnyDatabase 只在 admin 数据库中可用,赋予用户所有数据库的 dbAdmin 权限。
root 只在 admin 数据库中可用。超级账号,超级权限
更多关于用户权限的说明参照:https://docs.mongodb.com/manual/core/security-built-in-roles/
3:用户创建语法
{
user: "<name>",
pwd: "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>",
db: "<database>" } | "<role>",
...
]
}
语法说明:
user 字段:用户的名字;
pwd 字段:用户的密码;
cusomData 字段:为任意内容,例如可以为用户全名介绍;
roles 字段:指定用户的角色,可以用一个空数组给新用户设定空角色;
roles 字段:可以指定内置角色和用户定义的角色。
4:管理用户
到这里专门讲解用户管理了,因此配置当中开启用户认证,配置信息如下:
[root@mongodb ~]# cat /usr/local/mongo/bin/mongo.conf
dbpath=/usr/local/mongo/data/db
logpath=/usr/local/mongo/logs/mongodb.log
fork=true
auth=true
bind_ip=0.0.0.0
[root@mongodb ~]# systemctl restart mongod
[root@mongodb ~]# systemctl status mongod
进入管理数据库
创建管理用户,root 权限
> db.createUser({user: "root",pwd: "root",roles: [ { role: "root", db: "admin" } ]})
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
# 注意:
创建管理员角色用户的时候,必须到 admin 下创建。
删除的时候也要到相应的库下操作。
验证用户是否能用
> db.auth("root","root")
1 #返回1即可 若不生效请重启一下mongo
查看创建的管理员用户
一个常见的报错:
> show users
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.getUsers@src/mongo/shell/db.js:1763:1
shellHelper.show@src/mongo/shell/utils.js:859:9
shellHelper@src/mongo/shell/utils.js:766:15
@(shellhelp2):1:1
这种报错常常出现在没有授权的情况下,刚刚也只是创建了对应的用户名以及角色,但是还没有通过 root 用户进行登陆。
> show users
{
"_id" : "admin.root",
"userId" : UUID("c749fa1d-2707-45de-927b-8923c57e4327"),
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
登陆数据库
注意:用户在哪个数据库下创建的,最后加上什么库,这里自然选择 admin 库。
方法一:命令行中进行登陆
[root@mongodb ~]# mongo -uroot -proot admin
MongoDB shell version v5.0.6
connecting to: mongodb://127.0.0.1:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f3c843cf-c1dd-4913-bb79-3aa797653acb") }
MongoDB server version: 5.0.6
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
---
The server generated these startup warnings when booting:
2021-12-28T01:54:07.080-05:00: You are running this process as the root user, which is not recommended
2021-12-28T01:54:07.080-05:00: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'
2021-12-28T01:54:07.080-05:00: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. We suggest setting it to 'never'
2021-12-28T01:54:07.080-05:00: Soft rlimits for open file descriptors too low
2021-12-28T01:54:07.080-05:00: currentValue: 1024
2021-12-28T01:54:07.080-05:00: recommendedMinimum: 64000
---
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>
方法二:在数据库中进行登陆验证:
> use admin
switched to db admin
> db.auth("root","root")
1
> show tables
system.users
system.version
正常登陆之后,再次查看用户:
> show users
{
"_id" : "admin.root",
"userId" : UUID("c749fa1d-2707-45de-927b-8923c57e4327"),
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
忘记管理员密码怎么办
有时候可能会忘记管理员密码,需要对其进行重置,这个时候,有两种方式可以更新管理员密码。
如果连用户名都忘记了,那么我们首先需要更改 MongoDB 的配置,去掉用户名密码认证的功能,然后重启。
[root@mongodb ~]# cat /usr/local/mongo/bin/mongo.conf
dbpath=/usr/local/mongo/data/db
logpath=/usr/local/mongo/logs/mongodb.log
fork=true
auth=false
bind_ip=0.0.0.0
[root@mongodb ~]# systemctl restart mongod.service
[root@mongodb ~]# mongo
然后使用 mongo 命令进入到数据库,进行简单查询:
> use admin
switched to db admin
> show users
{
"_id" : "admin.root",
"userId" : UUID("c749fa1d-2707-45de-927b-8923c57e4327"),
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> show tables #或者通过查询表来得知
system.users
system.version
> db.system.users.find() #查询user表
{ "_id" : "admin.root", "userId" : UUID("c749fa1d-2707-45de-927b-8923c57e4327"), "user" : "root", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "tpY6oNYch1yvYRuo62GF8Q==", "storedKey" : "/noOIPnOd48jwxQM2c5+dxahlZ4=", "serverKey" : "lzg0C2/dgM0UqM3pGCOOAVQ9hgU=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "tBArvaTbkcVS7nt84a6wKa0Zm0HfzYAlqOiX7g==", "storedKey" : "yxn6m7Xx6JLe9Xcizqys3GhJInefBUVTELlJ5w7Cor8=", "serverKey" : "RB1xvt+UpZCycLrHCbw0yZ8eyvb8cH7xYlCFn4AJh6w=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
得知管理员用户的名称为 root 之后,就能够进行密码更新的操作了。
利用 db.changeUserPassword
> use admin
switched to db admin
> db.changeUserPassword('root','123')
然后重新开启用户认证,重启验证。
[root@mongodb ~]# cat /usr/local/mongo/bin/mongo.conf
dbpath=/usr/local/mongo/data/db
logpath=/usr/local/mongo/logs/mongodb.log
fork=true
auth=true
bind_ip=0.0.0.0
[root@mongodb ~]# systemctl restart mongod.service
> use admin
switched to db admin
> db.auth("root","123")
1
> show users
{
"_id" : "admin.root",
"userId" : UUID("c749fa1d-2707-45de-927b-8923c57e4327"),
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
按生产需求创建应用用户
因为目前用户规划都还比较简单,因此创建用户的时候,都是基于 admin 来进行。
1:创建某库的读写用户
创建 test 用户,权限为读写
> use test
switched to db test
> db.createUser({user: "test",pwd: "test",roles: [ { role: "readWrite", db: "test" } ]})
Successfully added user: {
"user" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
]
}
> show users
{
"_id" : "test.test",
"userId" : UUID("65a88b1f-4f2a-437e-85fb-999d9cfd255b"),
"user" : "test",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
注意:给哪个库创建用户,授权用户,都要先use到对应的库,否则将不生效,删除用户也是。
测试用户权限
> db.createCollection('d')
{ "ok" : 1 }
> db.getCollectionNames()
[ "d" ]
2,创建对某库的只读用户
在 test 库创建只读用户 test
> use test
switched to db test
> db.createUser({user: "test1",pwd: "test1",roles: [ { role: "read", db: "test" } ]})
Successfully added user: {
"user" : "test1",
"roles" : [
{
"role" : "read",
"db" : "test"
}
]
}
> show users
{
"_id" : "test.test",
"userId" : UUID("65a88b1f-4f2a-437e-85fb-999d9cfd255b"),
"user" : "test",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
{
"_id" : "test.test1",
"userId" : UUID("3c37067e-47df-483d-8c30-8f7c3faf886a"),
"user" : "test1",
"db" : "test",
"roles" : [
{
"role" : "read",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
登录 test 用户,并测试是否只读
> db.getCollectionNames()
[ "d" ]
> db.createCollection('e')
{
"ok" : 0,
"errmsg" : "not authorized on test to execute command { create: \"e\", lsid: { id: UUID(\"f05bebce-acfb-4283-ba16-ab14d6e4a8c8\") }, $db: \"test\" }",
"code" : 13,
"codeName" : "Unauthorized"
}
创建对多库不同权限的用户
创建对 test 为读写权限,对 eryajf 库为只读权限的用户
> use test #切换到test库
switched to db test
> db.createUser({user: "app",pwd: "app",roles: [ { role: "readWrite", db: "test" },{ role: "read", db: "test" }]}) #创建用户
Successfully added user: {
"user" : "app",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "test"
}
]
}
> show users #查看用户
{
"_id" : "test.app",
"userId" : UUID("e25d6c21-190a-44e4-8868-868a474fcf12"),
"user" : "app",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
注意,这个时候创建的用户,是基于 test 库创建的,那么后续登陆等操作,也都需要跟上 test 库,而不能够跟上 test 的库。如果跟上 test 的库,将会报如下错误:
[root@mongodb ~]# mongo -uapp -papp test
connecting to: mongodb://127.0.0.1:27017/test?gssapiServiceName=mongodb
connect@src/mongo/shell/mongo.js:344:17
@(connect):2:6
exception: connect failed
查看并测试用户
[root@mongodb ~]# mongo -uapp -papp test
connecting to: mongodb://127.0.0.1:27017/test?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("8cef0c4a-3f3d-4802-8926-79aea22db826") }
MongoDB server version: 4.0.10
> db.createCollection('a')
{ "ok" : 1 }
> db.getCollectionNames()
[ "a" ]
> use test
switched to db test
> db.getCollectionNames()
[ "a", "b", "c", "d" ]
更改用户权限
其实更改权限无非就是更改用户的角色,因为在 MongoDB 中,角色决定了不同用户的不同权限。
先查看一下当前用户的角色。
[root@mongodb ~]# mongo -uroot -ptest1 admin
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("dbda85c8-7a90-4143-a31c-7a8ea58b80cc") }
> use test
switched to db eryajf
> show users
{
"_id" : "test.test",
"userId" : UUID("3bd64373-13c5-4a47-95f9-92a2433c0bf4"),
"user" : "test",
"db" : "test",
"roles" : [
{
"role" : "readWrite", #可以看到test用户是readWrite的角色
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
{
"_id" : "test.test1",
"userId" : UUID("eb2e54b8-a036-40a8-b8d4-5c8f5548ad25"),
"user" : "test1",
"db" : "test",
"roles" : [
{
"role" : "read", #可以看到test1用户是read的角色
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
更改用户角色
[root@mongodb ~]# mongo -uroot -ptest1 admin
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("dbda85c8-7a90-4143-a31c-7a8ea58b80cc") }
> use test
switched to db eryajf
> db.updateUser("test",{roles:[{role:"dbAdmin",db:"test"}]})
> show users
{
"_id" : "test.test",
"userId" : UUID("3bd64373-13c5-4a47-95f9-92a2433c0bf4"),
"user" : "test",
"db" : "test",
"roles" : [
{
"role" : "dbAdmin", #可以看到权限已经更新
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
{
"_id" : "test.test1",
"userId" : UUID("eb2e54b8-a036-40a8-b8d4-5c8f5548ad25"),
"user" : "test1",
"db" : "test",
"roles" : [
{
"role" : "read",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
删除用户
删除 app 用户:先登录到 admin 数据库
[root@mongodb ~]# mongo -uroot -proot admin
connecting to: mongodb://127.0.0.1:27017/admin?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("6edeba63-e2bf-477c-a098-965767d105b6") }
>
进入 test 库删除 app 用户
> use test
switched to db test
> show users
{
"_id" : "test.app",
"userId" : UUID("e25d6c21-190a-44e4-8868-868a474fcf12"),
"user" : "app",
"db" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
},
{
"role" : "read",
"db" : "test"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
> db.dropUser("app")
true
> show users
到这里,基本上能够体会到,MongoDB 当中那些关于角色用户权限规则的定义与配置了,MongoDB 自身已经定义好了许多个角色,这些角色针对全局,而在创建用户的时候,用户,角色,库这三个概念又是分离的,因此要多多体会,去理解三者的关系。
其他授权
创建 app 数据库的管理员:先登录到 admin 数据库
> use app
switched to db app
> db.createUser({user: "admin",pwd: "admin",roles: [ { role: "dbAdmin", db: "app" } ]})
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "dbAdmin",
"db" : "app"
}
]
}
> show users
{
"_id" : "app.admin",
"userId" : UUID("01e196c8-2119-488b-9d11-b969db266aea"),
"user" : "admin",
"db" : "app",
"roles" : [
{
"role" : "dbAdmin",
"db" : "app"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
创建 app 数据库读写权限的用户并具有 clusterAdmin 权限,要当心,这个用户的权限可是相当大的。
> use app
switched to db app
> db.createUser({user: "super-app",pwd: "super-app",roles: [ { role: "readWrite", db: "app" },{ role: "clusterAdmin", db: "admin" }]})
Successfully added user: {
"user" : "super-app",
"roles" : [
{
"role" : "readWrite",
"db" : "app"
},
{
"role" : "clusterAdmin",
"db" : "admin"
}
]
}
> show users
{
"_id" : "app.super-app",
"userId" : UUID("7533af91-3063-4460-8cb5-f77061eb5680"),
"user" : "super-app",
"db" : "app",
"roles" : [
{
"role" : "readWrite",
"db" : "app"
},
{
"role" : "clusterAdmin",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}