MongoDB开启权限验证的方法

基本角色

  • root 这是超级管理员
  • userAdminAnyDatabase 这个角色拥有分配角色和用户的权限,但没有查写的权限
  • readWrite 有读写权限
  • read 有读权限

创建一个超级用户

use admin
db.createUser({
    user: "root",
    pwd: "pwd",
    roles: [{
      "role" : "root",
      "db" : "admin"
    }]
})

db 是指定数据库的名字,admin 是管理数据库。

开启认证

进入mongod.conf配置文件,将auth 改为true;重启mongo服务;

权限登录

mongo --host xxx -u adminUserName -p userPassword --authenticationDatabase admin

其他

查看当前用户的权限

db.runCommand({
    usersInfo: 'userName',
    showPrivileges: true
})

创建一般用户,也是用 createUser

db.createUser({
    user: 'user1',
    pwd: '12345',
    roles: [
        { role: 'read', db: 'db1' },
        { role: 'read', db: 'db2' },
        { role: 'read', db: 'db3' }
    ]
})

修改密码

use admin
db.changeUserPassword("username", "xxx")

查看用户信息

db.runCommand({ usersInfo: 'userName' })

修改密码和用户信息

db.runCommand({
    updateUser: 'username',
    pwd: 'xxx',
    customData: { title: 'xxx' }
})