博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mongoDB-权限控制
阅读量:6434 次
发布时间:2019-06-23

本文共 14429 字,大约阅读时间需要 48 分钟。

启动服务 D:\MongoDB\Server\3.6\bin>mongod.exe --dbpath D:\MongoDB\Server\3.6\data 扩展
无认证启动:mongod --port 27017 --dbpath /data/db
认证启动:mongod --auth --port 27017 --dbpath /data/db
连接:mongo --port 27017

查看MongoDB所有Role定义 $ ./mongo.exeMongoDB shell version v3.6.5connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.6.5use adminswitched to db admindb.getRoles(    {      rolesInfo: 1,      showPrivileges:false,      showBuiltinRoles: true    })[        {                "role" : "__queryableBackup",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "__system",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "backup",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "clusterAdmin",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "clusterManager",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "clusterMonitor",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "dbAdmin",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "dbAdminAnyDatabase",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "dbOwner",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "enableSharding",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "hostManager",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "read",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "readAnyDatabase",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "readWrite",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "readWriteAnyDatabase",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "restore",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "root",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "userAdmin",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        },        {                "role" : "userAdminAnyDatabase",                "db" : "admin",                "isBuiltin" : true,                "roles" : [ ],                "inheritedRoles" : [ ]        }]

创建一个用户(在数据库里新建用户,不指定db默认指向当前db

创建 db.createUser(用户名,密码,拥有的角色。角色可以写多个)

use testswitched to db testdb.createUser(   {     user: "banana",     pwd: "123456",     roles: [ "readWrite" ]   })Successfully added user: { "user" : "banana", "roles" : [ "readWrite" ] }db.getUsers()[    {        "_id" : "test.banana",        "user" : "banana",        "db" : "test",        "roles" : [            {                "role" : "readWrite",                "db" : "test"            }        ]    }]

创建一个用户(在admin数据库里新建用户

(可以写多个role-db组合)

use adminswitched to db admindb.createUser(   {     user: "apple",     pwd: "qwer",     roles: [ {role:"read",db:"test"} ]   })Successfully added user: {    "user" : "apple",    "roles" : [        {            "role" : "read",            "db" : "test"        }    ]}db.getUsers()[    {        "_id" : "admin.apple",        "user" : "apple",        "db" : "admin",        "roles" : [            {                "role" : "read",                "db" : "test"            }        ]    }]

修改密码

db.changeUserPassword("apple", "niudun")

 

删除用户(只会删除当前数据库里面的存在的用户

db.dropUser("apple")true

 

 

 下面测试权限,再创建2个用户

test

use testswitched to db testdb.createUser(   {     user: "peach",     pwd: "taozi",     roles: [        {role : "readWrite", db : "test"},        {role : "readWrite", db : "test2"}     ]   })Successfully added user: {    "user" : "peach",    "roles" : [        {            "role" : "readWrite",            "db" : "test"        },        {            "role" : "readWrite",            "db" : "test2"        }    ]}db.getUsers()[    {        "_id" : "test.banana",        "user" : "banana",        "db" : "test",        "roles" : [            {                "role" : "readWrite",                "db" : "test"            }        ]    },    {        "_id" : "test.peach",        "user" : "peach",        "db" : "test",        "roles" : [            {                "role" : "readWrite",                "db" : "test"            },            {                "role" : "readWrite",                "db" : "test2"            }        ]    }]

 

admin

use admin switched to db admin db.createUser(   {     user: "pineapple",     pwd: "boluo",     roles: [ "readWrite", "userAdmin" ]   })Successfully added user: { "user" : "pineapple", "roles" : [ "readWrite", "userAdmin" ] }db.getUsers()[    {        "_id" : "admin.apple",        "user" : "apple",        "db" : "admin",        "roles" : [            {                "role" : "read",                "db" : "test"            }        ]    },    {        "_id" : "admin.pineapple",        "user" : "pineapple",        "db" : "admin",        "roles" : [            {                "role" : "readWrite",                "db" : "admin"            },            {                "role" : "userAdmin",                "db" : "admin"            }        ]    }]

 

 

先把服务开启认证重启

D:\MongoDB\Server\3.6\bin>mongod.exe --auth --dbpath D:\MongoDB\Server\3.6\data

 

 第一种连接方法(先进去再认证)

 

[d:\MongoDB\Server\3.6\bin]$ mongo.exeMongoDB shell version v3.6.5connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.6.5db.stats(){    "ok" : 0,    "errmsg" : "not authorized on test to execute command { dbstats: 1.0, scale: undefined, $db: \"test\" }",    "code" : 13,    "codeName" : "Unauthorized"}

 

 

 

 

你访问之前需要认证

db.auth("banana","123456")1

 

 查看数据库状态

db.stats(){    "db" : "test",    "collections" : 2,    "views" : 0,    "objects" : 4,    "avgObjSize" : 73,    "dataSize" : 292,    "storageSize" : 32768,    "numExtents" : 0,    "indexes" : 2,    "indexSize" : 32768,    "fsUsedSize" : 41188569088,    "fsTotalSize" : 332861009920,    "ok" : 1}

 

查看集合(也可以用show collections)

show tablesaaamy_collection

 

查看集合里面的数据(已有的)

db.aaa.find(){ "_id" : NumberLong(1), "name" : "BBB", "_class" : "com.example.demo.entity.Book" }{ "_id" : NumberLong(2), "name" : "CCC", "_class" : "com.example.demo.entity.Book" }

 

切换admin数据库

use adminswitched to db adminshow tables2018-08-10T12:59:43.551+0800 E QUERY    [thread1] Error: listCollections failed: {    "ok" : 0,    "errmsg" : "not authorized on admin to execute command { listCollections: 1.0, filter: {}, $db: \"admin\" }",    "code" : 13,    "codeName" : "Unauthorized"} :_getErrorWithCode@src/mongo/shell/utils.js:25:13DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:941:1DB.prototype.getCollectionInfos@src/mongo/shell/db.js:953:19DB.prototype.getCollectionNames@src/mongo/shell/db.js:964:16shellHelper.show@src/mongo/shell/utils.js:842:9shellHelper@src/mongo/shell/utils.js:739:15@(shellhelp2):1:1

 

可以得出结论:用户存在哪一个数据库,就只能在那一个数据库上认证

先用Apple认证(因为没有赋予高级角色,所以不能访问高级内容)

db.auth("apple","niudun")1show dbs2018-08-10T13:07:10.786+0800 E QUERY    [thread1] Error: listDatabases failed:{    "ok" : 0,    "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0, $db: \"admin\" }",    "code" : 13,    "codeName" : "Unauthorized"} :_getErrorWithCode@src/mongo/shell/utils.js:25:13Mongo.prototype.getDBs@src/mongo/shell/mongo.js:65:1shellHelper.show@src/mongo/shell/utils.js:849:19shellHelper@src/mongo/shell/utils.js:739:15@(shellhelp2):1:1

 

我们知道这个apple是拥有test的读取权限的,但是它却存储在admin里,我们用它访问test试试

use adminswitched to db admindb.auth("apple","niudun")1use testswitched to db testshow tablesaaamy_collectiondb.aaa.find(){ "_id" : NumberLong(1), "name" : "BBB", "_class" : "com.example.demo.entity.Book" }{ "_id" : NumberLong(2), "name" : "CCC", "_class" : "com.example.demo.entity.Book" }

 

 

我们还有一个pineapple,没有与test的联系,看他能不能访问

use adminswitched to db admindb.auth("pineapple","boluo")1use testswitched to db testshow tables2018-08-10T13:51:49.650+0800 E QUERY    [thread1] Error: listCollections failed: {    "ok" : 0,    "errmsg" : "not authorized on test to execute command { listCollections: 1.0, filter: {}, $db: \"test\" }",    "code" : 13,    "codeName" : "Unauthorized"} :_getErrorWithCode@src/mongo/shell/utils.js:25:13DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:941:1DB.prototype.getCollectionInfos@src/mongo/shell/db.js:953:19DB.prototype.getCollectionNames@src/mongo/shell/db.js:964:16shellHelper.show@src/mongo/shell/utils.js:842:9shellHelper@src/mongo/shell/utils.js:739:15@(shellhelp2):1:1

 

 那么暂时得出结论:创建在admin里面的用户,如果赋予访问其他数据库的权限,则在admin上通过认证之后,可以访问它权限范围内的数据库;否则不能。

 那么普通数据库呢?

use testswitched to db testdb.auth("peach","taozi")1db.stats(){    "db" : "test",    "collections" : 2,    "views" : 0,    "objects" : 4,    "avgObjSize" : 73,    "dataSize" : 292,    "storageSize" : 32768,    "numExtents" : 0,    "indexes" : 2,    "indexSize" : 32768,    "fsUsedSize" : 41192714240,    "fsTotalSize" : 332861009920,    "ok" : 1}use test2switched to db test2show tablesbbbdb.bbb.find(){ "_id" : ObjectId("5b6d29e778212a9cb2bbd958"), "name" : "test2.bbb.data" }

 

这个peach用户拥有对test2数据库的访问权限。那么说:无论admin还是普通数据库,只要对创建的用户赋予访问其它数据库的权限,都是可以访问的。

如果说,我不想去指定用户能不能访问某个数据库,用户也可以访问。那可以通过赋予高级权限来搞定

// 这里的pineapple拥有创建用户权限,所以这里可以直接创建新用户并赋予权限 use admin switched to db admin db.auth("pineapple","boluo") 1 db.createUser(   {     user: "peach",     pwd: "taozi",     roles: ["dbAdminAnyDatabase"]   })Successfully added user: { "user" : "peach", "roles" : [ "dbAdminAnyDatabase" ] }db.getUsers()[    {        "_id" : "admin.apple",        "user" : "apple",        "db" : "admin",        "roles" : [            {                "role" : "read",                "db" : "test"            }        ]    },    {        "_id" : "admin.peach",        "user" : "peach",        "db" : "admin",        "roles" : [            {                "role" : "dbAdminAnyDatabase",                "db" : "admin"            }        ]    },    {        "_id" : "admin.pineapple",        "user" : "pineapple",        "db" : "admin",        "roles" : [            {                "role" : "readWrite",                "db" : "admin"            },            {                "role" : "userAdmin",                "db" : "admin"            }        ]    }]db.auth("peach","taozi")1use testswitched to db testshow tablesaaamy_collection use test2 switched to db test2 show tables bbb

 

无意间又发现:不同数据库的用户即使相同,它们之间也互不影响!因为我的peach用户在test数据库也有了,admin中也有。

大概就这么多,有新的会补上

第二种连接方法(登录的时候就认证)

mongo.exe --port 27017 -u "用户名" -p "密码" --authenticationDatabase "认证数据库"

 

..

[d:\MongoDB\Server\3.6\bin]$ mongo.exe --port 27017 -u "peach" -p "taozi" --authenticationDatabase "admin"MongoDB shell version v3.6.5connecting to: mongodb://127.0.0.1:27017/MongoDB server version: 3.6.5db.stats(){    "db" : "test",    "collections" : 2,    "views" : 0,    "objects" : 4,    "avgObjSize" : 73,    "dataSize" : 292,    "storageSize" : 32768,    "numExtents" : 0,    "indexes" : 2,    "indexSize" : 32768,    "fsUsedSize" : 41195212800,    "fsTotalSize" : 332861009920,    "ok" : 1}2018-08-10T14:42:32.210+0800 I CONTROL  [thread2] CTRL_CLOSE_EVENT signal2018-08-10T14:42:32.210+0800 I CONTROL  [consoleTerminate] got CTRL_CLOSE_EVENT, will terminate after current cmd ends2018-08-10T14:42:32.211+0800 I CONTROL  [consoleTerminate] shutting down with code:12[d:\MongoDB\Server\3.6\bin]$ mongo.exe --port 27017 -u "pineapple" -p "boluo" --authenticationDatabase "admin"MongoDB shell version v3.6.5connecting to: mongodb://127.0.0.1:27017/MongoDB server version: 3.6.5db.stats(){    "ok" : 0,    "errmsg" : "not authorized on test to execute command { dbstats: 1.0, scale: undefined, $db: \"test\" }",    "code" : 13,    "codeName" : "Unauthorized"}

 

我先用peach登录,因为它拥有所有数据库的权限,所以默认进来test,可以直接访问的。然而我用pineapple登录,它仅仅拥有admin的权限,所以进来test是不能访问的。

我想说什么呢,我以为会自动进入你输入的证数据库,结果不是。

 

最后总结一下用到的命令

命令 说明
mongod.exe --auth --dbpath D:\MongoDB\Server\3.6\data 启动服务(认证状态)
use [db] 切换数据库,不存在即创建
show dbs 查看数据库列表
db.dropDatabase() 删除当前数据库
db.stats() 查看数据库状态信息
show tables/collections 查看当前数据库里的表(集合)
mongo.exe --port 27017 -u "peach" -p "taozi" --authenticationDatabase "admin" 以用户名密码认证登录
use admindb.createUser( { user: "peach", pwd: "taozi", roles: [ { role: "readWrite", db: "test" }, "userAdmin" ] } )
创建用户,可以指定role-db。只有role-默认当前数据库

   use admin

   db.changeUserPassword("peach", "123")

修改密码。当前数据库下的已存在的用户
use admindb.dropUser("peach")
删除用户
db.dropAllUsers()
删除所有用户
use admindb.getUser("peach")
获取用户信息
use admindb.getUsers()
获取所有用户
use admindb.auth("peach", "123" )
认证
   db.collection.find() 列出集合里面的数据
   db.collection.dataSize() 集合大小
   db.collection.drop() 删除集合
db.collection.insert( { item: "card", qty: 15 } )
添加数据

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

概念对比:

MongoDB MySQL
数据库 数据库
集合
文档 表里的一条数据

 

转载于:https://www.cnblogs.com/LUA123/p/9455298.html

你可能感兴趣的文章
MongoDB、Hbase、Redis等NoSQL优劣势、应用场景
查看>>
FTP服务
查看>>
android应用市场、社区客户端、漫画App、TensorFlow Demo、歌词显示、动画效果等源码...
查看>>
SpringCloud服务的平滑上下线
查看>>
C# 基于Arcface SDK实现人脸识别和注册
查看>>
使用python发送QQ邮件
查看>>
C++ 之 多态(非常非常重要,重点在后面)
查看>>
gitlab的仓库迁移到新的gitlab
查看>>
Java垃圾收集算法
查看>>
Mahout推荐算法中的其他数据结构
查看>>
php 二维数组排序
查看>>
OSChina 周四乱弹 ——今天家里只有我和女室友,我想……
查看>>
OSChina 周四乱弹 —— 大型翻车现场
查看>>
在一个页面中显示多个activity
查看>>
Hibernate4.x之Session--常用方法
查看>>
MongoDB Windows环境安装及配置
查看>>
ios 中字符串怎么换行
查看>>
XStream基本使用
查看>>
黑莓刷机
查看>>
NGUI v301 官方详解 Example 2 - Interaction
查看>>