MongoDB权限
更新:HHH   时间:2023-1-7


1. 添加用户
MongoDB shell version: 1.8.2
connecting to: 127.0.0.1:30000/test
>
>
>
> use admin
switched to db admin
> db.addUser('admin','admin')
{
                "user" : "admin",
                "readOnly" : false,
                "pwd" : "7c67ef13bbd4cae106d959320af3f704"
}
>

2. 带上--auth参数后重启
$MONGODB_HOME/bin/mongod --fork --logpath=$MONGODB_HOME/logs/mongodb.log --dbpath=$DATA_PATH --port=$MONGODB_PORT --auth

3. 测试
MongoDB shell version: 1.8.2
connecting to: 127.0.0.1:30000/test
>
> use admin
switched to db admin
> show collections
Sat Aug    6 11:16:45 uncaught exception: error: {
                "$err" : "unauthorized db:admin lock type:-1 client:127.0.0.1",
                "code" : 10057
}
switched to db admin
> db.auth('admin','admin')
1
> show collections
system.indexes
system.users
>
没有执行db.auth('admin','admin')之前会报错,说是未授权

4. Java客户端调用也需要使用用户名和密码,只需简单地加上一句
db.authenticate("admin", "admin".toCharArray());

5. 在admin下添加的用户是超级管理员,可以访问任何数据库,用超级管理员可以为单个数据库添加用户,这个用户只能访问他所在的数据库
> use test
switched to db test
> db.addUser("test","test")
{
                "user" : "test",
                "readOnly" : false,
                "pwd" : "a6de521abefc2fed4f5876855a3484f5"
}
6. 在未授权的情况下,依然可以执行
db.shutdownServer()停掉节点
所以运行mongodb的服务器端口一定要严格授权访问


返回MongoDB数据库教程...