MongoDB Series 3: MongoDB user permission operations

Source: Internet
Author: User
Tags createindex

MongoDB Series 3: MongoDB user permission operations

After preliminary research on configuration and basic understanding, the following section describes MongoDB's user permission operations.

Brief Introduction:

Like all other databases, permission management is similar. Mongodb stores all user information in the admin database collection system. users and stores the user name, password, and database information. By default, authorization is not enabled for mongodb. As long as you can connect to this server, you can connect to mongod. To enable security authentication, you need to change the configuration file parameter auth.

1. Check which databases already exist under MongoDB

show dbs 
The result is as follows:


Because the admin library already exists locally, you can directly learn the following content. If you have not installed MongoDB

If the admin library is found, you can use the following command to create the admin library and create an admin user, which will be used later.

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

2. Go to the admin database and check what it contains.


After entering the table, we found that the table contains three sets: Index, user, and version.

3. Execute the find command of the set separately to view the data in the three sets. [Note: The set here is equivalent to the table of the database we usually use]

> db.system.users.find();{ "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "DDWOrIFkjoeF7mFGNOgsMA==", "storedKey" : "Q7JLL0AziNLBtngVJYglQ+lZRvE=", "serverKey" : "qRC3s0HCrmIw2My5s0zAmHQUzvM=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ]}> db.system.indexes.find();{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "admin.system.version" }{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "admin.system.users" }{ "v" : 1, "unique" : true, "key" : { "user" : 1, "db" : 1 }, "name" : "user_1_db_1", "ns" : "admin.system.users" }> db.system.version.find();{ "_id" : "authSchema", "currentVersion" : 5 }

4. Enable auth now

Edit the configuration file mongo. config we wrote in the preliminary study, and add this line at the bottom.

auth=true 

Now we restart the Mongod service, and we will find that we have no access permission, as shown in:


Just now, an account admin was created in the admin database. Connect to the admin database first (other databases fail ):

> db.auth("admin","admin");Error: 18 Authentication failed.0> use admin;switched to db admin> db.auth("admin","admin");1

0: indicates that the authorization fails. 1: indicates that the authorization is successful.


To verify that the corresponding set cannot be viewed without authorization, we switch the database to the test database and execute the show collections command. The result is as follows.

It turns out that after permission authentication is enabled, you must have permissions to access the corresponding set of databases.

> use testswitched to db test> show collections;2015-07-19T15:51:59.069+0800 E QUERY    Error: listCollections failed: {        "ok" : 0,        "errmsg" : "not authorized on test to execute command { listCollections: 1.0 }",        "code" : 13}    at Error (<anonymous>)    at DB._getCollectionInfosCommand (src/mongo/shell/db.js:646:15)    at DB.getCollectionInfos (src/mongo/shell/db.js:658:20)    at DB.getCollectionNames (src/mongo/shell/db.js:669:17)    at shellHelper.show (src/mongo/shell/utils.js:625:12)    at shellHelper (src/mongo/shell/utils.js:524:36)    at (shellhelp2):1:1 at src/mongo/shell/db.js:646

5. Role authorization for the created users

There are two types of Role authorization: one is to directly create a user in the current database and grant related permissions. For example, create an admin user in the admin database. Another scenario is

Grant the user created in admin the permission to operate other databases. The authorization command is as follows:

# Grant a role: db. grantRolesToUser ("userName", [{role: "<role>", db: "<database>"}]) # cancel role: db. grantRolesToUser ("userName", [{role: "<role>", db: "<database>"}])
Run the following command in the admin database:

 db.grantRolesToUser( "admin" , [ { role: "dbOwner", db: "test" } ]) ;

Then we switched to the test database. We were surprised to find that the admin user can also execute the show collections command.

Note:

Use the db. auth ("admin", "admin") command to log on to the database that contains this user. However, after successful login, if the current user has

To access other databases, you can directly switch to the corresponding database and execute relevant data operation commands.

Therefore, for convenience, we recommend that you create a user in the current database directly when creating each database, so that you do not need to switch back and forth.

6. Create a custom role and authorize the role

# Create a role and authorize the database. createRole ({role: "testRole", privileges: [{resource: {db: "mydb", collection: ""}, actions: ["find"]}], roles: []}) # Add Privileges to the role db. grantPrivilegesToRole ("testRole", [{resource: {db: "mydb", collection: ""}, actions: ["update", "insert ", "remove"]}])

# Change the role roles and update all the roles values. Similarly, Privileges can update and replace db. updateRole ("testRole", {roles: [{role: "readWrite", db: "mydb"}] },{ w: "majority "})

For more information about roles, refer to the official document for extraction and summarization as follows:

Role category

Role

Permissions and Roles

(The case may vary in this document. For more information, see the official documentation)

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 and createCollection are stored in system. profile.

DbOwner

Role: readWrite, dbAdmin, userAdmin

UserAdmin

ChangeCustomData, ChangePassword, CreateRole, CreateUser,

DropRole, DropUser, GrantRole, RevokeRole, ViewRole, viewUser

Cluster Administration Roles

ClusterAdmin

Roles: clusterManager, clusterMonitor, and hostManager

ClusterManager

AddShard, ApplicationMessage, CleanupOrphaned, FlushRouterConfig,

ListShards, RemoveShard, ReplSetConfigure, ReplSetGetStatus,

ReplSetStateChange, Resync,

 

EnableSharding, MoveChunk, SplitChunk, splitVector

ClusterMonitor

ConnPoolStats, cursorInfo, getdomainlineopts, 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

The insert and update permissions are provided in the mms. backup document of the admin database.

List all databases: listDatabases

List all set indexes: listIndexes

 

The following query operations are available: find

* Non-system set

* System set: system. indexes, system. namespaces, system. js

* Set: admin. system. users and admin. system. roles

Restore

Non-system set, system. js, admin. system. users, admin. system. roles, and system. users 2.6 provide the following permissions:

CollMod, createCollection, createIndex, dropCollection, insert

 

List all databases: listDatabases

System. users: find, remove, update

All-Database Roles

ReadAnyDatabase

Read-Only permission for all databases: read

List all databases in the Cluster: listDatabases

ReadWriteAnyDatabase

Read and Write Permissions for all databases: readWrite

List all databases in the Cluster: listDatabases

UserAdminAnyDatabase

Provide all user data management permissions: userAdmin

Cluster: authSchemaUpgrade, invalidateUserCache, listDatabases

Admin. system. users and admin. system. roles:

CollStats, dbHash, dbStats, find, killCursors, planCacheRead

CreateIndex, dropIndex

DbAdminAnyDatabase

Grant all database administrator permissions: dbAdmin

List all databases in the Cluster: listDatabases

Superuser Roles

Root

Role: dbOwner, userAdmin, userAdminAnyDatabase

ReadWriteAnyDatabase, dbAdminAnyDatabase,

UserAdminAnyDatabase, clusterAdmin

Internal Role

_ System

Any operations on any database in the Cluster


OK. Now the simple permission operation has been introduced. In section 4, we will introduce the combined use of MongoDB and JDBC.

Copyright statement: Reprinted with the blog address to respect the author's Labor achievements. Welcome to http://blog.csdn.net/zgs_shmilyto grow together.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.