MongoDB 基础 -安全性-(权限操作)

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 和其他所有数据库一样,权限的管理都差不多一样。mongodb存储所有的用户信息在admin 数据库的集合system.users中,保存用户名、密码和数据库信息。mongodb默认不启用授权认证,只要能连接到该服务器,就可连接到mongod。

和其他所有数据库一样,权限的管理都差不多一样。mongodb存储所有的用户信息在admin 数据库的集合system.users中,保存用户名、密码和数据库信息。mongodb默认不启用授权认证,只要能连接到该服务器,就可连接到mongod。若要启用安全认证,需要更改配置文件参数auth。

 https://docs.mongodb.com/manual/reference/method/db.dropAllUsers/

https://docs.mongodb.com/v2.6/tutorial/add-user-to-database/

以下测试理解

 

查看数据库:

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. > show dbs  

发现 admin 竟然没有!~

 

 

找了好久,找不到相关说明,于是直接创建用户admin

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. use admin  
  2.   
  3.   
  4. db.createUser(  
  5.   {  
  6.     user: "admin",  
  7.     pwd: "admin",  
  8.     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]  
  9.   }  
  10. )  

成功创建,再查询admin中的集合,有数据了!

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. > show collections  
  2. system.indexes  
  3. system.users  
  4. system.version  


查看3个集合的信息:

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. > db.system.users.find();  
  2. { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "cFISfpbm04pmIFpqiL340g==", "storedKey" : "WG1DSEEEHUZUBjsjsnEA4RFVY2M=", "serverKey" : "9Lm+IX6l9kfaE/4C25/ghsQpDkE=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }  
  3. >   
  4. > db.system.indexes.find();  
  5. { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "admin.system.version" }  
  6. { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "admin.system.users" }  
  7. { "v" : 1, "unique" : true, "key" : { "user" : 1, "db" : 1 }, "name" : "user_1_db_1", "ns" : "admin.system.users" }  
  8. >   
  9. > db.system.version.find();  
  10. { "_id" : "authSchema", "currentVersion" : 5 }  
  11. >   


现在启用 auth:
[root@localhost ~]# vi /etc/mongod.conf

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. auth=true  


重启 mongod 服务:

 

[root@localhost ~]# service mongod restart

 

直接默认登录,查看集合,发现无权操作了:

[root@localhost ~]# mongo

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. [root@localhost ~]# mongo  
  2. MongoDB shell version: 3.0.2  
  3. connecting to: test  
  4. > show dbs  
  5. 2015-05-09T21:57:03.176-0700 E QUERY    Error: listDatabases failed:{  
  6.     "ok" : 0,  
  7.     "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",  
  8.     "code" : 13  
  9. }  
  10.     at Error (<anonymous>)  
  11.     at Mongo.getDBs (src/mongo/shell/mongo.js:47:15)  
  12.     at shellHelper.show (src/mongo/shell/utils.js:630:33)  
  13.     at shellHelper (src/mongo/shell/utils.js:524:36)  
  14.     at (shellhelp2):1:1 at src/mongo/shell/mongo.js:47  
  15. >   



 

刚才在数据库 admin 创建了一个账户 admin ,先到数据admin进来连接(其他db则失败):

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. [root@localhost ~]# mongo  
  2. MongoDB shell version: 3.0.2  
  3. connecting to: test  
  4. >  
  5. > db.auth("admin","admin")  
  6. Error: 18 Authentication failed.  
  7. 0  
  8. > use mydb  
  9. switched to db mydb  
  10. > db.auth("admin","admin")  
  11. Error: 18 Authentication failed.  
  12. 0  
  13. > use admin  
  14. switched to db admin  
  15. > db.auth("admin","admin")  
  16. 1  
  17. >   


db.auth("admin","admin") 返回值为1,说明登录成功!~db.auth("admin","admin") 记录是不存在的,执行完后这一行在shell中不会记录历史。

 

 

所以现在创建另一个用户"myuser"

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. db.createUser(  
  2.   {  
  3.     user: "myuser",  
  4.     pwd: "myuser",  
  5.     roles: [ { role: "readWrite", db: "mydb" } ]  
  6.   }  
  7. )  


也可以增删角色:

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. #授予角色:db.grantRolesToUser( "userName" , [ { role: "<role>", db: "<database>" } ])  
  2.   
  3. db.grantRolesToUser( "myuser" , [ { role: "dbOwner", db: "mydb" } ])  
  4.   
  5.   
  6. #取消角色:db.grantRolesToUser( "userName" , [ { role: "<role>", db: "<database>" } ])  
  7.   
  8. db.revokeRolesFromUser( "myuser" , [ { role: "readWrite", db: "mydb" } ])  


因为在admin数据库创建的,只能在 admin 数据库中登录:

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. > db.auth("myuser","myuser")  
  2. Error: 18 Authentication failed.  
  3. 0  
  4. >   
  5. > db  
  6. mydb  
  7. > use admin  
  8. switched to db admin  
  9. > db.auth("myuser","myuser");  
  10. 1  
  11. >   


此时是可以切换到所在的数据库进行相关操作:

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. > use mydb  
  2. switched to db mydb  
  3. >   
  4. > db.tab.save({"id":999});  
  5. WriteResult({ "nInserted" : 1 })  
  6. >   
  7. > db.tab.find({"id":999});  
  8. { "_id" : ObjectId("554ef5ac1b590330c00c7d02"), "id" : 999 }  
  9. >   
  10. > show collections  
  11. system.indexes  
  12. tab  
  13. >   


在创建用户时可以在其数据库中创建,这样不用每次都进入admin数据库登录后再切换。如在数据库"mydb"创建用户"userkk"。

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. use admin  
  2.   
  3. db.auth("admin","admin")  
  4.   
  5. use mydb  
  6.   
  7. db.createUser(  
  8.   {  
  9.     user: "userkk",  
  10.     pwd: "userkk",  
  11.     roles: [ { role: "dbOwner", db: "mydb" } ]  
  12.   }  
  13. )  
  14.   
  15. db.auth("userkk","userkk")  



 

------------------------------------------------------------------------------------------------------------------

                                                      华丽分割

------------------------------------------------------------------------------------------------------------------

 

现在授权测试:

 

#先访问到admin数据库

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. use admin  
  2.   
  3. db.auth("admin","admin")  

 

 

#切换到 mydb ,在数据库 mydb 中创建角色
#roles: 创建角色"testRole"在数据库 "mydb" 中
#privileges: 该角色可查看"find"数据库"mydb"的所有集合
#db.dropRole("testRole")

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. use mydb  
  2.   
  3. db.createRole({   
  4.  role: "testRole",  
  5.  privileges: [{ resource: { db: "mydb", collection: "" }, actions: [ "find" ] }],  
  6.  roles: []  
  7. })  


#在admin数据库生成集合system.roles。查看角色。

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. > use admin  
  2. switched to db admin  
  3. >   
  4. > show collections  
  5. system.indexes  
  6. system.roles  
  7. system.users  
  8. system.version  
  9. >   
  10. > db.system.roles.find();  
  11. { "_id" : "mydb.testRole", "role" : "testRole", "db" : "mydb", "privileges" : [ { "resource" : { "db" : "mydb", "collection" : "" }, "actions" : [ "find" ] } ], "roles" : [ ] }  
  12. >   


#回到mydb,在数据库mydb中创建用户并授予角色"testRole"
#db.dropUser("userkk")

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. use mydb  
  2.   
  3. db.createUser(  
  4.   {  
  5.     user: "userkk",  
  6.     pwd: "userkk",  
  7.     roles: [ { role: "testRole", db: "mydb" } ]  
  8.   }  
  9. )  


退出mongodb,重新登录进行操作。发现只能使用find
>exit

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. [root@localhost ~]# mongo  
  2. MongoDB shell version: 3.0.2  
  3. connecting to: test  
  4. > use mydb  
  5. switched to db mydb  
  6. >   
  7. > db.auth("userkk","userkk")  
  8. 1  
  9. >   
  10. > db.tab.find({"id":999})  
  11. { "_id" : ObjectId("554ef5ac1b590330c00c7d02"), "id" : 999 }  
  12. >   
  13. > db.tab.insert({"id":1000})  
  14. WriteResult({  
  15.     "writeError" : {  
  16.         "code" : 13,  
  17.         "errmsg" : "not authorized on mydb to execute command { insert: \"tab\", documents: [ { _id: ObjectId('554f145cdf782b42499d80e5'), id: 1000.0 } ], ordered: true }"  
  18.     }  
  19. })  
  20. >   


给角色 "testRole"  添加3个 “Privileges”权限: "update", "insert", "remove"。再重新操作。

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. use admin  
  2.   
  3. db.auth("admin","admin")  
  4.   
  5. use mydb  
  6.   
  7. #添加Privileges给角色  
  8. db.grantPrivilegesToRole("testRole",  
  9.  [{ resource: { db: "mydb", collection: "" },actions: [ "update", "insert", "remove" ]}  
  10. ])  
  11.   
  12.   
  13. exit #退出mongodb重新登录  
  14.   
  15.   
  16. use mydb  
  17.   
  18. db.auth("userkk","userkk")  
  19.   
  20.   
  21. #增删数据可以操作了!~  
  22. db.tab.insert({"id":1000})  
  23. db.tab.find({"id":1000})  
  24. db.tab.remove({"id":1000})  
  25.   
  26.   
  27. #此时admin的角色记录为:  
  28. > db.system.roles.find();  
  29. { "_id" : "mydb.testRole", "role" : "testRole", "db" : "mydb", "privileges" : [ { "resource" : { "db" : "mydb", "collection" : "" }, "actions" : [ "find", "insert", "remove", "update" ] } ], "roles" : [ ] }  
  30. >   


#更改角色 roles,把roles值全部更新。同样Privileges也可以更新替换!~

 

 

[plain]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. use admin  
  2.   
  3. db.auth("admin","admin")  
  4.   
  5. use mydb  
  6.   
  7. db.updateRole("testRole",{ roles:[{ role: "readWrite",db: "mydb"}]},{ w:"majority" })  
  8.   
  9. db.auth("userkk","userkk")  
  10.   
  11. show dbs  



 

 

关于角色,参考官方文档提取总结如下:

 

角色分类

角色

权限及角色

(本文大小写可能有些变化,使用时请参考官方文档)

Database User Roles

read

CollStats,dbHash,dbStats,find,killCursors,listIndexes,listCollections

readWrite

CollStats,ConvertToCapped,CreateCollection,DbHash,DbStats,

DropCollection,CreateIndex,DropIndex,Emptycapped,Find,

Insert,KillCursors,ListIndexes,ListCollections,Remove,

RenameCollectionSameDB,update

Database Administration Roles

dbAdmin

collStats,dbHash,dbStats,find,killCursors,listIndexes,listCollections,

dropCollection 和 createCollection 在 system.profile

dbOwner

角色:readWrite, dbAdmin,userAdmin

userAdmin

ChangeCustomData,ChangePassword,CreateRole,CreateUser,

DropRole,DropUser,GrantRole,RevokeRole,ViewRole,viewUser

Cluster Administration Roles

clusterAdmin

角色:clusterManager, clusterMonitor, hostManager

clusterManager

AddShard,ApplicationMessage,CleanupOrphaned,FlushRouterConfig,

ListShards,RemoveShard,ReplSetConfigure,ReplSetGetStatus,

ReplSetStateChange,Resync,

 

EnableSharding,MoveChunk,SplitChunk,splitVector

clusterMonitor

connPoolStats,cursorInfo,getCmdLineOpts,getLog,getParameter,

getShardMap,hostInfo,inprog,listDatabases,listShards,netstat,

replSetGetStatus,serverStatus,shardingState,top

 

collStats,dbStats,getShardVersion

hostManager

applicationMessage,closeAllDatabases,connPoolSync,cpuProfiler,

diagLogging,flushRouterConfig,fsync,invalidateUserCache,killop,

logRotate,resync,setParameter,shutdown,touch,unlock

Backup and Restoration Roles

backup

提供在admin数据库mms.backup文档中insert,update权限

列出所有数据库:listDatabases

列出所有集合索引:listIndexes

 

对以下提供查询操作:find

*非系统集合

*系统集合:system.indexes, system.namespaces, system.js

*集合:admin.system.users 和 admin.system.roles

restore

非系统集合、system.js,admin.system.users 和 admin.system.roles 及2.6 版本的system.users提供以下权限:

collMod,createCollection,createIndex,dropCollection,insert

 

列出所有数据库:listDatabases

system.users :find,remove,update

All-Database Roles

readAnyDatabase

提供所有数据库中只读权限:read

列出集群所有数据库:listDatabases

readWriteAnyDatabase

提供所有数据库读写权限:readWrite

列出集群所有数据库:listDatabases

userAdminAnyDatabase

提供所有用户数据管理权限:userAdmin

Cluster:authSchemaUpgrade,invalidateUserCache,listDatabases

admin.system.users和admin.system.roles:

collStats,dbHash,dbStats,find,killCursors,planCacheRead

createIndex,dropIndex

dbAdminAnyDatabase

提供所有数据库管理员权限:dbAdmin

列出集群所有数据库:listDatabases

Superuser Roles

root

角色:dbOwner,userAdmin,userAdminAnyDatabase

readWriteAnyDatabase, dbAdminAnyDatabase,

userAdminAnyDatabase,clusterAdmin

Internal Role

__system

集群中对任何数据库采取任何操作

 

 

 

参考:mongo Shell Methods  , Built-In RolesSecurity Methods in the mongo Shell

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
4月前
|
NoSQL JavaScript 前端开发
如何使用 Node.js 连接和操作 MongoDB 数据库?
如何使用 Node.js 连接和操作 MongoDB 数据库?
232 2
|
3月前
|
NoSQL MongoDB Python
深入了解 Python MongoDB 操作:排序、删除、更新、结果限制全面解析
使用 sort() 方法对结果进行升序或降序排序。 sort() 方法接受一个参数用于“字段名”,一个参数用于“方向”(升序是默认方向)。
67 0
|
7月前
|
JSON NoSQL MongoDB
mongodb基本操作,增删改查,查询,索引,权限机制
mongodb基本操作,增删改查,查询,索引,权限机制
|
22天前
|
缓存 NoSQL 关系型数据库
【MongoDB】MongoDB更新操作时是否立刻fsync到磁盘?
【4月更文挑战第2天】【MongoDB】MongoDB更新操作时是否立刻fsync到磁盘?
|
23天前
|
消息中间件 NoSQL Kafka
云原生最佳实践系列 5:基于函数计算 FC 实现阿里云 Kafka 消息内容控制 MongoDB DML 操作
该方案描述了一个大数据ETL流程,其中阿里云Kafka消息根据内容触发函数计算(FC)函数,执行针对MongoDB的增、删、改操作。
|
3月前
|
机器学习/深度学习 自然语言处理 NoSQL
|
3月前
|
存储 NoSQL MongoDB
Python小姿势 - Python操作MongoDB数据库
Python小姿势 - Python操作MongoDB数据库
|
6月前
|
NoSQL API MongoDB
Python使用PyMongo4.x操作MongoDB总结
PyMongo是一个Python编程语言中用于连接和操作MongoDB数据库的库。它提供了丰富的功能和API,使开发者能够在Python中轻松地进行MongoDB的数据交互和管理。
84 2
|
7月前
|
NoSQL JavaScript Java
MongoDB 入门教程系列之三:使用 Restful API 操作 MongoDB
MongoDB 入门教程系列之三:使用 Restful API 操作 MongoDB
79 0
|
7月前
|
存储 NoSQL Java
MongoDB 入门教程系列之二:使用 Spring Boot 操作 MongoDB
MongoDB 入门教程系列之二:使用 Spring Boot 操作 MongoDB
99 0