mongodb 3.x用户认证

mongodb 认证(authentication)

认证与授权是紧密关联的,但是认证不同于授权。认证是确认一个用户的身份,允许用户登录数据库,而授权是赋予认证的用户各种权限,是用户有访问的不同资源和进行各种操作的权限。

1. mongodb认证机制

2. mongodb认证

客户端认证(用户认证)

客户端认证是对连接到mongd或mongos的客户端进行认证确认

  • 1 通过mongo shell认证

    • 在命令行连接mongod或mongos实例时,使用如下参数:–username,–password,–authenticationDatabase

    • 直接在命令行连接mongd或mongos,然后在mongo shell中切换到认证数据库后运行authenticate命令或db.auth()方法

  • 2 在编程语言的驱动中认证

    参考驱动文档

Internal Authentication(集群数据库成员间认证)

在集群部署中,除了对客户端进行认证,集群中各成员的数据库实例间也需要进行认证(Internal Authentication)。如果开启了Internal Authentication,客户端认证也会被开启,连接数据库是必须进行客户端认证。

Internal Authentication 方法:
* keyfile
* x.509

3. 创建用户

use admin
switched to db admin
db.createUser(
...   {
...     user: 'admin',
...     pwd: 'admin',
...     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
...   }
... )
Successfully added user: {
    "user" : "admin",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}

4. 内置角色:

1. 数据库用户角色:read、readWrite;
2. 数据库管理角色:dbAdmin、dbOwner、userAdmin;
3. 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
4. 备份恢复角色:backup、restore;
5. 所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
6. 超级用户角色:root (如果用户同时有dbOwner 、userAdmin、userAdminAnyDatabase三个角色,就间接或直接提供了系统超级用户的访问)

5. 每个角色具体权限:

1. read:允许用户读取指定数据库
2. readWrite:允许用户读写指定数据库
3. dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
4. userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
5. clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
6. readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
7. readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
8. userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
9. dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
10. root:只在admin数据库中可用。超级账号,超级权限

6. 开启认证

参考文档

7. 演示

1. 进入mongo shell,查看数据库报错,提示没有权限。

[mongo@mongo ~]$ mongodb/bin/mongo
MongoDB shell version v3.4.1
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.1
> show dbs
2016-12-26T12:18:56.060+0800 E QUERY    [main] Error: listDatabases failed:{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
        "code" : 13,
        "codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:755:19
shellHelper@src/mongo/shell/utils.js:645:15
@(shellhelp2):1:1

2. 切换到admin数据库,对admin用户进行认证,1表示认证成功。

> use admin
switched to db admin
> db.auth('admin','123456')
1

3. 切换到test数据库,新建用户

> use test
switched to db test
> db
test
> db.createUser({
... user:'weiyang',
... pwd:'weiyang',
... roles:[{role:'readWrite',db:'test'}]
... })
Successfully added user: {
        "user" : "weiyang",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                }
        ]
}

4. 查看当前数据的用户

> show users
{
        "_id" : "test.weiyang",
        "user" : "weiyang",
        "db" : "test",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                }
        ]
}

5. 在test数据库中插入数据

> db.test.insert({a:'1'})
WriteResult({
        "writeError" : {
                "code" : 13,
                "errmsg" : "not authorized on test to execute command { insert: \"test\", documents: [ { _id: ObjectId('58609da684679bee11c966b4'), a: \"1\" } ], ordered: true }"
        }
})

插入数据时报错,提示没有权限,只是因为虽然新建用户并给了合适的权限,但是该新用户并没有在当前数据库经过认证。接着认证用户,并插入读取刚插入的文档。

> db.auth('weiyang','weiyang')
1
> db.test.insert({a:'1'})
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("58609ef384679bee11c966b5"), "a" : "1" }
在admin下创建的帐号,不能直接在其他库验证,只能在帐号创建库下认证,再去其他库进行操作
> use admin
switched to db admin
> db.createUser({
... ... ... user:'dba',
... ... ... pwd:'dba',
... roles:[{role:'readWrite',db:'test'}]
... })
Successfully added user: {
        "user" : "dba",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                }
        ]
}

> use test
switched to db test
> db.auth('ada','dba')
Error: Authentication failed.
0

在admin数据库中添加的dba用户在test数据库下无法认证。
说明数据库帐号与数据库关联,哪里创建哪里认证。

8. 查看所有用户

> use admin
switched to db admin
> db.system.users.find().pretty()
{
        "_id" : "admin.admin",
        "user" : "admin",
        "db" : "admin",
        "credentials" : {
                "SCRAM-SHA-1" : {
                        "iterationCount" : 10000,
                        "salt" : "eRoNrRq46X3/v8OVQuUeYg==",
                        "storedKey" : "LIWYhSFf410huy6q51o0riJGOj4=",
                        "serverKey" : "NH1ORreaf6ZirMQQaV7XaEHZ3ys="
                }
        },
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
{
        "_id" : "sample.wei.yang",
        "user" : "wei.yang",
        "db" : "sample",
        "credentials" : {
                "SCRAM-SHA-1" : {
                        "iterationCount" : 10000,
                        "salt" : "8q+5f2aJocedFdT7QvxWCg==",
                        "storedKey" : "OgczIU984kXv63sN99gWQjdfpgs=",
                        "serverKey" : "q6DkTIYuWTZwZhrkm9CLnuAz0ps="
                }
        },
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "sample"
                }
        ]
}
{
        "_id" : "admin.test",
        "user" : "test",
        "db" : "admin",
        "credentials" : {
                "SCRAM-SHA-1" : {
                        "iterationCount" : 10000,
                        "salt" : "OXd4mRMDW7Hjmv0yfffGZQ==",
                        "storedKey" : "MCNYJuS3L1GXOcH2Xmh0yd/7ta0=",
                        "serverKey" : "y0xBeQlsV0Aj7OZ8IGRPl/ZbuOA="
                }
        },
        "roles" : [
                {
                        "role" : "read",
                        "db" : "sample"
                },
                {
                        "role" : "readWrite",
                        "db" : "admin"
                }
        ]
}
{
        "_id" : "test.weiyang",
        "user" : "weiyang",
        "db" : "test",
        "credentials" : {
                "SCRAM-SHA-1" : {
                        "iterationCount" : 10000,
                        "salt" : "ld1LSq7L+Q8EF22hzpgK3w==",
                        "storedKey" : "8rrE+/0V+QIjfRcVKGE+LSE5iyU=",
                        "serverKey" : "7S93z95RBxcQDEyx85MFK1QFhYE="
                }
        },
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                }
        ]
}
{
        "_id" : "admin.dba",
        "user" : "dba",
        "db" : "admin",
        "credentials" : {
                "SCRAM-SHA-1" : {
                        "iterationCount" : 10000,
                        "salt" : "O0SpJWwT5Md7IQD7cCD/pw==",
                        "storedKey" : "7lXc1VBmBJ+WNQFyLtlBo/oEMK4=",
                        "serverKey" : "+PCmRcu2WuWTLUiA2xOYDFtqTGc="
                }
        },
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                }
        ]
}

9. 用户和角色方法

详细参见官方文档:
https://docs.mongodb.com/manual/reference/method/#role-management

10. Role Management

Name    Description
db.createRole() Creates a role and specifies its privileges.
db.updateRole() Updates a user-defined role.
db.dropRole()   Deletes a user-defined role.
db.dropAllRoles()   Deletes all user-defined roles associated with 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.getRole()    Returns information for the specified role.
db.getRoles()   Returns information for all the user-defined roles in a database.
User Management

11. Name Description

db.auth()                       Authenticates a user to a database.
db.createUser()               Creates a new user.
db.updateUser()               Updates user data.
db.changeUserPassword()       Changes an existing user’s password.
db.removeUser()                 Deprecated. Removes a user from a database.
db.dropAllUsers()               Deletes all users associated with a database.
db.dropUser()                       Removes a single user.
db.grantRolesToUser()           Grants a role and its privileges to a user.
db.revokeRolesFromUser()        Removes a role from a user.
db.getUser()                    Returns information about the specified user.
db.getUsers()                   Returns information about all users associated with a database.
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/uevol14/article/details/53885779
文章标签: mongodb
个人分类: mongoDB
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭