MongoDb Auth认证 用户权限设置

MongoDB 权限配置

MongoDB 默认没有管理员账号,如果需要开启权限必须先添加管理员账号。

  • 切换到 admin (Collection-集合)
1
2
3
4
> use admin
switched to db admin
> show collections
system.version
  • 创建超级管理员用户
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
> db.createUser({user:'root',pwd:'root',roles:["root"]})
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
> show users
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
## 官方🌰
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
## 官方🌰
use reporting
db.createUser(
{
user: "reportsUser",
pwd: "12345678",
roles: [
{ role: "read", db: "reporting" },
{ role: "read", db: "products" },
{ role: "read", db: "sales" },
{ role: "readWrite", db: "accounts" }
]
}
)
  • 切到所在集合,创建用户
1
2
3
4
5
6
7
8
9
10
11
12
13
>use mycollections
>db.createUser(
{
user: "reportsUser",
pwd: "12345678",
roles: [
{ role: "read", db: "reporting" },
{ role: "read", db: "products" },
{ role: "read", db: "sales" },
{ role: "readWrite", db: "accounts" }
]
}
)

MongoDB 开启Auth认证

修改配置文件mongod.conf

1
2
3
4
5
6
security:
authorization: enabled
#authorization: disabled

## 网络上很多资料是以下配置,
auth=true

Enable Access Control
MongoDB does not enable access control by default. You can enable authorization using the –auth or the security.authorization setting. Enabling internal authentication also enables client authorization.

官方配置文档

Laravel中使用MongoDB

安装扩展包composer require jenssegers/mongodb.
修改config/database.php配置文件

1
2
3
4
5
6
7
8
9
10
11
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGO_DB_HOST', 'localhost'),
'port' => env('MONGO_DB_PORT', 27017),
'database' => env('MONGO_DB_DATABASE'),
'username' => env('MONGO_DB_USERNAME'),
'password' => env('MONGO_DB_PASSWORD'),
'options' => [
'database' => env('MONGO_DB_DATABASE') // sets the authentication database required by mongo 3
]
],

MongoDB是强类型语言,PHP中对MongoDB操作时要注意类型问题!

以下两个查询会得到不一样的结果:

1
2
> db.users.find({user_id:1})
> db.users.find({user_id:"1"})

Reference

  1. https://blog.csdn.net/kk185800961/article/details/45619863
  2. https://www.jianshu.com/p/f5afc6488f9e
  3. https://docs.mongodb.com/manual/core/authorization/