One, foreword
By default, mongod is listening on 127.0.0.1, any client can connect to 27017 directly, default is [unauthorized mode] (do not need to authenticate any permissions, do not need to authenticate the account, enter mongo in the command window), This is extremely unsafe (especially in a production environment, but of course it doesn’t matter if you’re playing by yourself). MongoDB uses role-based Access Control (RBAC) to manage users’ Access to instances. The permission to access database resources and perform database operations is controlled by granting users one or more roles. Users cannot access instances until roles are assigned to them. This paper mainly introduces the Role-based Access Control (RBAC) permission management mechanism of MongoDB. Its core is to grant certain permissions to each user. Users need to verify before connecting to MongoDB. Permissions determine what operations (such as adding, deleting, modifying, searching, and creating indexes) a user can perform on a set of resources (such as a DB or a specific collection).
2. Introduction to RBAC authority model
RBAC(Role-based Access Control) : Role-based Access Control, introduces the permission system design of this model. Instead of directly associating users with rights, users are indirectly assigned rights by associating roles with users and rights with roles. Thus achieving decoupling. RBAC has been divided into the following versions during its development. RBAC0, RBAC1, RBAC2, RBAC3.
- RBAC0: This is the initial form of RBAC and the original and simplest version of RBAC;
- RBAC1: Optimization based on RBAC0, adding layers of roles (that is, sub-roles). Sub-roles can inherit all permissions of their parent roles.
- RBAC2: Another optimization based on RBAC0, which adds some restrictions on roles: roles are mutually exclusive, role capacity, etc.
- RBAC3: The most complex and comprehensive RBAC model, which integrates the optimized parts of RBAC1 and RBAC2 on the basis of RBAC0.
There are several key terms in the model:
- User: The operator of the system interface and access, i.e. the logged-in User itself, has a User ID(defined UUID)
- Role: a user with the same operation rights. That is, a user has several identities and a user can have several roles
- Access: The authorization to Access an interface or perform an operation
3. Role of MongoDB System (RBAC)
MongoDB provides a set of built-in roles to perform basic database operations. Each built-in role provides the user access to all sets of non-system classes at the database level within the role database, as well as to all system collections at the collection level. MongoDB provides built-in database user roles and database management roles on each database, but only other built-in roles on the admin database.
3.1 user
MongoDB implements role-based access control. Therefore, to create a user, specify a role for the user. Before creating a user, ensure that:
- Create user userAdmin or userAdminAnyDatabase in the admin database as the user to manage users.
- Enable access control to authenticate login users so that creating users makes sense.
3.1.1 Creating a User managed By Users Before enabling access control, you need to create userAdmin or userAdminAnyDatabase in the admin database as the user managed by users, and then you can use this user to create users of other roles. This user acts as a manager for all other users.
3.2 the role
In MongoDB, users are granted the operation permissions of database resources by roles. The permissions of each role can be explicitly specified, or inherited from other roles, or both.
3.2.1 MongoDB Built-in Roles
- Database user roles: read and readWrite.
- Database management roles: dbAdmin, dbOwner, and userAdmin.
- Cluster management roles: clusterAdmin, clusterManager, clusterMonitor, and hostManager.
- Backup and restoration roles: Backup and restore.
- All database roles: readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, and dbAdminAnyDatabase
- Super user role: root
- Internal roles: __system
Common built-in roles are as follows:
role | Permissions described |
---|---|
read | Can read any data in the specified database. |
readWrite | You can read and write any data in a specified database, including creating, renaming, and deleting collections. |
readAnyDatabase | You can read any data in all databases (except the databases Config and local). |
readWriteAnyDatabase | You can read and write any data from any database (except the databases Config and local). |
dbAdmin | You can read the specified database, clean, modify, and compress the database, obtain statistics, and check the database. |
dbAdminAnyDatabase | You can read any database and clean, modify, compress, get statistics, perform checks, and so on (except for databases Config and local). |
clusterAdmin | You can manage an entire cluster or database system. |
userAdmin | Users can be created and modified in the specified database. |
userAdminAnyDatabase | You can create and modify users in the specified database (except for database config and local). |
3.2.1.1 Database User Roles
- read
The read role can read all non-system collections and subscribe to system collections such as System. indexes, System. js, and system.namespaces.
The permissions of this role include command operations: changeStream, collStats, dbHash, dbStats, find, killCursors, listIndexes, and listCollections.
- readWrite
The readWrite role has the permission of the read role. The readWrite role has the permission to modify non-system set data, but only system set system.js.
The role permissions include command operations: CollStats, convertToCapped, createCollection, dbHash, dbStats, dropCollection, createIndex, dropIndex, FIND, Insert, killCursors, L IstIndexes, listCollections, remove, renameCollectionSameDB, update.
3.2.1.2 Database Management Roles
- dbAdmin
The dbAdmin role contains permissions to perform certain administrative tasks (schema-related, indexing, and collecting statistics). This role does not contain permissions for user and role management.
Include commands for system collections (system.indexes, System. namespaces, system.profile) CollStats, dbHash, dbStats, find, killCursors, listIndexes, listCollections, dropCollection and CreateCollection (System.profile only)
For non-system collection containing command operations: BypassDocumentValidation, collMod, collStats, Compact, convertToCapped, createCollection, createIndex, dbStats, dropCollection, D RopDatabase, dropIndex, enableProfiler, reIndex, renameCollectionSameDB, repairDatabase, storageDetails, and VALIDATE
- dbOwner
The dbOwner role has all data management rights. That is, the permissions of roles readWrite, dbAdmin, and userAdmin are included.
- userAdmin
The userAdmin role has permissions to create and modify roles and users for the current database. This role allows any permissions to be granted to any other user (including itself), so this role also provides indirect access to the superuser (root) and, if restricted to the admin data, to the cluster administration.
The role permissions include command operations: ChangeCustomData, changePassword, createRole, createUser, dropRole, dropUser, grantRole, revokeRole, setAuthenticationRestrictio N, viewRole, viewUser.
3.2.1.3 Cluster Management Roles
- clusterManager
The clusterManager role has permissions for cluster monitoring and management operations. Users with this role can access the Config and local databases in the cluster.
This role contains command actions for the entire cluster: AddShard, appendOplogNote, applicationMessage, Cleanuporphopted, flushRouterConfig, listSessions (3.6 Added), listShards, removeShard, replSetConfigure, replSetGetConfig, replSetGetStatus, replSetStateChange, and resync.
Contains command operations for all databases in the cluster: enableSharding, moveChunk, splitChunk, splitVector.
For the cluster config database and local database contains command operation can refer to the official document: docs.mongodb.com/manual/refe…
- clusterMonitor
The clusterMonitor role has read-only permissions for monitoring tools. Tools such as MongoDB Cloud Manager and Ops Manager.
This role contains command actions for the entire cluster: CheckFreeMonitoringStatus (new) 4.0, connPoolStats, getCmdLineOpts, getLog, getParameter, getShardMap, hostInfo, inprog, listDataba Ses, listSessions (added in 3.6), listShards, NetStat, replSetGetConfig, replSetGetStatus, serverStatus, setFreeMonitoring (4.0 added), shardingState, Top.
CollStats, dbStats, getShardVersion, indexStats, useUUID(added in 3.6).
For the cluster config database and local database contains command operation can refer to the official document: docs.mongodb.com/manual/refe…
- hostManager
The hostManager role has the operation rights to monitor and manage database servers.
This role contains command actions for the entire cluster: ApplicationMessage, closeAllDatabases, connPoolSync, cpuProfiler, flushRouterConfig, fsync, invalidateUserCache, killAnyCursor (4.0 new), killAnySession (3.6 new), Killop, logRotate, resync, setParameter, shutdown, Touch, unlock.
Commands are included for all databases in the cluster: killCursors, repairDatabase.
- clusterAdmin
The clusterAdmin role has the highest operation rights for MongoDB cluster management. This role has all the permissions of the clusterManager, clusterMonitor, and hostManager roles and has the permissions of the dropDatabase operation commands.
3.2.1.4 Backing up and Restoring Roles
- backup
The backup role has the minimum permission to backup MongoDB data.
For all database resources in MongoDB, there are command operations: listDatabases, listCollections, and listIndexes.
For the entire cluster there are command operations: appendOplogNote, getParameter, listDatabases.
Provide find operation privileges for the following database resources:
- For all non-system collections in the cluster, including its own Config database and local database;
- For system collections in the cluster: System.indexes, System.namespaces, system.js, and System.profile;
- Roles for admin.system. Users and admin.system.
- Set. The config Settings;
- The System. Users collection prior to version 2.6.
The config.setting collection also has insert and update permissions.
- restore
The restore role contains permission to restore MongoDB data (except for the System.profile collection) from backup files.
Note the following for the restore role:
- Mongorestore attempts to rebuild the System. profile collection if it is included in the backup and the restore target database does not have the System. profile collection. Therefore, the executive user needs to have additional createCollection and convertToCapped operation rights for the System. profile collection;
- If you specify the –oplogReplay option when executing the restore command, then the permissions contained in the restore role cannot replay oplog. If you need to replay Oplog, you need to grant custom roles containing any permissions to any resources in the instance only to the user executing Mongorestore.
For the entire cluster contains the command operation: getParameter.
For all non-system collection containing command operations: BypassDocumentValidation, changeCustomData, changePassword, collMod, convertToCapped, createCollection, createIndex, createRole GrantRole, insert, revokeRole, viewRole, viewUser.
About restore roles contain other command operation can refer to the official document: docs.mongodb.com/manual/refe…
3.2.1.5 All Database Roles
The following roles only exist in the admin database and apply to all databases except config and Local.
- readAnyDatabase
The readAnyDatabase role has read-only permissions on all databases except Config and local. The listDatabases command is used for the entire cluster.
Prior to MongoDB3.4, this role had access to the Config and local databases. In the current version, if you need to read from these two databases, you need to grant the user the read role on the admin database for these two databases.
- readWriteAnyDatabase
The readWriteAnyDatabase role has read and write permissions to all databases except Config and Local. The listDatabases command is used for the entire cluster.
Prior to MongoDB3.4, this role had read and write permissions to the Config and local databases. In the current version, if you need to read and write to these two databases, you need to grant the user the readWrite role on the admin database for these two databases.
- userAdminAnyDatabase
The userAdminAnyDatabase role has user administration privileges similar to the userAdmin role for all databases except config and Local.
For a cluster containing commands, perform the following operations: authSchemaUpgrade, invalidateUserCache, and listDatabases.
For the system collections Admin.system. users and admin.system.roles contain command operations: CollStats, dbHash, dbStats, find, killCursors, planCacheRead, createIndex, dropIndex.
This role does not restrict the operations that users can perform to grant permissions. Therefore, users with a role can grant permissions beyond the scope of the role to themselves or other users, or make themselves a superuser. The userAdminAnyDatabase role can also be considered as a superuser role in MongoDB.
- dbAdminAnyDatabase
The dbAdminAnyDatabase role has administrative rights similar to the dbAdmin role for all databases except the Config and local databases. The listDatabases command is used for the entire cluster.
Prior to MongoDB3.4, this role had administrative rights to the Config and local databases. In the current version, if you want to manage these two databases, you need to grant the user the dbAdmin role on the admin database for these two databases.
3.2.1.6 Super User Role
The following roles contain permissions to grant any user any permissions on any database. This means that users can grant themselves any permissions on any database if they have one of the following roles.
- DbOwner role (scoped to admin database)
- UserAdmin role (scoped to admin database)
- UserAdminAnyDatabase role
The following roles have all operation rights for all database resources.
- root
The root role contains all permissions of the roles readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase, clusterAdmin, Restore, and Backup combined.
3.2.1.7 Internal Roles
- __system
MongoDB grants this role to user objects that represent cluster members, such as replica set members or Mongos instances. This role allows users to have permissions for all required database operations. Do not grant this role to application users or other administrator users.
3.2.2 User-defined Roles
Although MongoDB provides a number of built-in roles, sometimes built-in roles don’t have all the permissions they need, so MongoDB also provides a way to create custom roles. When creating a custom role, go to the specified database because MongoDB uniquely identifies the role by database and role name.
Except for roles created in the admin database, the rights of custom roles created in other databases apply only to the database where the role resides and can inherit the rights of other roles in the database. Custom roles created in the admin database are not subject to this restriction.
MongoDB stores all role information in the System. roles set in the admin database. You are not advised to directly access this set. You can use role management commands to view and edit customized roles.
3.3 permissions
Permissions consist of the specified database resource and the actions that are allowed on the specified resource.
- Resources include databases, collections, partial collections, and clusters.
- Actions Include adding, deleting, modifying, and querying resources (CRUD).
A role can contain one or more existing roles. A newly created role inherits all permissions of the roles. In the same database, a newly created role can inherit the rights of other roles. A role created in the admin database can inherit the rights of roles in other databases.
To view role permissions, run the following command:
> db. RunCommand ({rolesInfo:"<rolename>"}) db.runcommand ({rolesInfo: {role:"<rolename>", db: "<database>"}} db. RunCommand ({rolesInfo: ["<rolename>",
{ role: "<rolename>", db: "<database>"},... ] }) // Query the permissions of all roles (only user-defined roles) > db.runCommand({rolesInfo: 1}) // Query the permissions of all roles (including built-in roles) > db.runCommand({rolesInfo: 1}) 1, showBuiltinRoles:true })
Copy the code
Iv. Account password setting
MongoDB passwords differ somewhat from traditional data such as mysql: MongoDB usernames and passwords are database-specific rather than system-wide. All the DB databases require passwords.
4.1 Creating Management Roles for All Databases
4.1.1 Viewing All Databases
Run cmd.exe, go to the bin directory of the Mongodb installation directory, and run mongo.exe to go to the Mongodb CLI.
- The Mongo command interface is displayed
// Enter the mongo command line interface $mongoCopy the code
- Viewing all databases
// View all databases (admin database is not available in the new MongoDB version, but that does not prevent step 2.) $ show dbsCopy the code
- Query result display
> show dbs
admin 0.000GB
config 0.000GB
local0.000 GBCopy the code
4.1.2 Accessing the Admin Database
- Accessing the admin database
// Enter the admin database $use adminCopy the code
- The results showed
> use admin
switched to db admin
Copy the code
4.1.3 Creating an Administrator Account
Users in MongoDB are based on identity roles. The role of the administrator account is userAdminAnyDatabase. The admin user manages accounts and cannot perform operations such as shutting down the database.
- Enter the
kuaizhidao
The database
// Add admin user (user name :admin and password :admin are customizable. ) the createUser ({user:"admin", / / accountpwd:"admin"// Roles: [{roles:"userAdminAnyDatabase"// Role userAdminAnyDatabase db:"admin"}]})Copy the code
- The creation result is displayed
Successfully added user: {
"user" : "admin"."roles": [{"role" : "userAdminAnyDatabase"."db" : "admin"}}]Copy the code
- The Settings are complete and you can enter
show users
ordb.getUsers()
Check whether the configuration is successful.
> show users {"_id" : "admin.admin"."userId" : UUID("a245d242-6ce6-4239-a77d-4318038b46b0"),
"user" : "admin"."db" : "admin"."roles": [{"role" : "userAdminAnyDatabase"."db" : "admin"}]."mechanisms" : [
"SCRAM-SHA-1"."SCRAM-SHA-256"]}Copy the code
4.1.4 Super Administrator root
Now add a user root to the admin database of MongoDB. The role is root, and the password is root. MongoDB can establish permission authentication for each database, that is, you can specify which database a user can log in to. The root role is used to shutdown the db.shutdownServer() database. In MongoDB, the admin database is a special database. The user of this database can access all the databases in MongoDB.
- Example Add a super administrator
db.createUser({
user: "root".pwd: "root",
roles: [ {
role: "root",
db: "admin"}]})Copy the code
- The creation result is displayed
Successfully added user: {
"user" : "root"."roles": [{"role" : "root"."db" : "admin"}}]Copy the code
- The Settings are complete and you can enter
show users
ordb.getUsers()
Check whether the configuration is successful.
// View the user under the current library {"_id" : "admin.admin"."userId" : UUID("a245d242-6ce6-4239-a77d-4318038b46b0"),
"user" : "admin"."db" : "admin"."roles": [{"role" : "userAdminAnyDatabase"."db" : "admin"}]."mechanisms" : [
"SCRAM-SHA-1"."SCRAM-SHA-256"]} {"_id" : "admin.root"."userId" : UUID("2e178964-7b97-4502-b013-b0db87755758"),
"user" : "root"."db" : "admin"."roles": [{"role" : "root"."db" : "admin"}]."mechanisms" : [
"SCRAM-SHA-1"."SCRAM-SHA-256"]}Copy the code
4.2 Creating a Management Role for a Single Database
In addition to setting up the super administrator of the database, we can also set up a separate administrator for each database. It only has certain permissions to manipulate individual data. Here we take kuaizhidao database as an example, to kuaizhidao to configure an account.
Note: between each different database, you can create one or more accounts, between each database account, password are independent, can not access each other!
4.2.1 Viewing All Databases
Run cmd.exe, go to the bin directory of the Mongodb installation directory, and run mongo.exe to go to the Mongodb CLI.
- The Mongo command interface is displayed
// Enter the mongo command line interface $mongoCopy the code
- Viewing all databases
// View all databases (admin database is not available in the new MongoDB version, but that does not prevent step 2.) $ show dbsCopy the code
- Query result display
> show dbs
admin 0.000GB
config 0.000GB
kuaizhidao 0.000GB
local0.000 GBCopy the code
4.2.2 Accessing yourDatabase
- Enter yourDatabase database kuaizhidao
// Enter yourDatabase database $use kuaizhidaoCopy the code
- The results showed
> use kuaizhidao
switched to db kuaizhidao
Copy the code
4.2.3 Creating an Account
Now add a kauizhidao administrator to MongoDB’s kuaizhidao database. “DbOwner” stands for the database owner role, has the highest privileges of the database, password is kuaizhidao, such as new index, etc. When the account administrator and super administrator, can create users for their own database. At this time, you must switch to the local database to create a user, otherwise the created user still belongs to admin.
For read/write roles, set permission to Role: “readWrite”
- Creating a database User
DbOwner db.createUser({user: kuaizhidao: kuaizhidao: kuaizhidao);"kuaizhidao"// User namepwd: "kuaizhidao"// Roles: [{roles:"dbOwner"// role db:"kuaizhidao"}]})Copy the code
Note: if you do not set an account for the admin table, it is useless to set an account password for the business table.
- The result is displayed
Successfully added user: {
"user" : "kuaizhidao"."roles": [{"role" : "dbOwner"."db" : "kuaizhidao"}}]Copy the code
- The Settings are complete and you can enter
show users
ordb.getUsers()
Check whether the configuration is successful.
// View the user under the current library {"_id" : "kuaizhidao.kuaizhidao"."userId" : UUID("9670ee67-011d-4036-a78d-5523026a196d"),
"user" : "kuaizhidao"."db" : "kuaizhidao"."roles": [{"role" : "dbOwner"."db" : "kuaizhidao"}]."mechanisms" : [
"SCRAM-SHA-1"."SCRAM-SHA-256"]}Copy the code
4.3 Database User Operations
Deleting a user must be done by the account administrator, so switch to the admin role
$ use admin
db.auth("root","root")
Copy the code
4.3.1 Deleting a User
- Deleting a User
Db.system.users. remove({user:"XXXXXX"})
Copy the code
// dropUser db.dropuser ('admin')
Copy the code
- Deleting all Users
Db.system.users.remove ({})Copy the code
4.3.2 Changing a User Password
// Change the user password db.updateuser ('admin', {pwd: 'root'})
Copy the code
4.3.3 Password Authentication
// Password authentication db.auth('root'.'root')
Copy the code
4.4 Enabling Authentication
Authentication can be enabled by the –auth parameter or by setting security: authorization: Enabled in the configuration file Mongod. CFG.
4.4.1 Modifying a Configuration File
Go to the MongoDB installation directory, go to the bin folder, open the mongod.cfg file, and find the following configuration:
#security:
Copy the code
Is amended as:
#security:
security:
authorization: enabled
Copy the code
4.4.2 restart mongo
$ net start MongoDB
Copy the code
5. Common commands
5.1 Running PowerShell as a System Administrator
Win+R
5.2 Link database Mongo
$ mongo
MongoDB shell version v4.4.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("e5c1430e-0b85-4c6b-82e1-d63f16f6a10d"} MongoDB server version: 4.4.6 -- The server generated these startup warnings when booting: 2021-05-13T13:12:11.023+08:00: Access control is not enabledfor the database. Read and write access to data and configuration is unrestricted
---
Copy the code
5.3 Checking the Database show DBS
5.4 Switching to the admin database: use admin
5.5 Creating super Administrator Account db.createuser ()
Db.createuser ({user:’root’, PWD :’root’,roles:[‘root’]})
In the command, user follows the user name, PWD follows the password, and roles is a created user role
5.6 Switch to blog data Use blog(blog is a database created by myself)
5.7 Creating a Common Account db.createuser ()
Db.createuser ({user:’ Carrie ‘, PWD :’ Carrie ‘,roles:[‘readWrite’]}
5.8 Uninstalling the Mongodb Service
1. Stop the service. Net stop mongodb
2.mongod –romove
5.9 Creating the mongodb Service
Example: Mongod – logpath = “C: \ Program Files \ mongo \ Server \ \ log \ mongod 4.2 log” — dbpath = “C: \ Program Files \ mongo \ Server \ \ data “4.2 – install – auth
Mongod –logpath= specifies the directory to store the output logs
–dbpath= specifies the database storage directory
–install –auth means you must be an administrator to manipulate data
5.10 Enabling the mongodb service net start mongodb
5.11 Using an Account to Connect to the Database in a Project
mongoose.connect('mongodb://user:password@localhost:port/database'Const mongoose = require(const mongoose = require('mongoose'); // Connect to database mongoose.connect('mongodb://carrie:carrie@localhost:27017/kuaizhidao',
{ useNewUrlParser: true, useUnifiedTopology: true}).then(() => console.log('Database connection successful'))
.catch(() => console.log('Database connection failed'))
Copy the code