Detailed explanation of MongoDB security authentication

1. Introduction to user and role permissions

By default, the MongoDB instance does not enable user access control when it is started and running. You can freely connect to the instance on the local server of the instance to perform various operations. MongoDB will not perform user authentication on the connection client request, which is very dangerous.

The MongoDB official website says that in order to ensure the security of MongoDB, you can take the following steps:
(1) Use a new port. If you can connect to the default port 27017 once you know the ip, it is not very safe.
(2) Set up the network environment of MongoDB. It is best to deploy MongoDB to the internal network of the company server, so that the external network cannot be accessed. The internal access of the company uses vpn and so on.
(3) Enable security authentication. For authentication, the internal authentication method between servers must be set at the same time, and the account password authentication method for the client to connect to the cluster must be set at the same time.

In order to forcibly enable user access control (user authentication), you need to use the option --auth when starting the MongoDB instance or
add options to the specified startup configuration file --auth=true.

Related concepts:

  • Enable access control:
    MongoDB uses role-based access control (Role-Based Access Control, RBAC) to manage user access to instances. By granting one or more roles to the user to control the user's access to database resources and database operations, the user cannot access the instance before assigning a role to the user. Add the option --auth when the instance starts or specify the option in the startup configuration file--auth=true

  • Role:
    In MongoDB, the user is granted the operation authority of the corresponding database resource through the role. The authority of each role can be specified explicitly, or by inheriting the authority of other roles, or the authority of both.

  • Permissions:
    Permissions consist of specified database resources (resources) and operations (actions) allowed on specified resources. Resources include: databases, collections, partial collections, and clusters. Actions include: add, delete, modify, and check (CRUD) operations on resources.

One or more existing roles can be included in the role definition, and the newly created role will inherit all the permissions of the included roles. In the same database, newly created roles can inherit the permissions of other roles, and roles created in the admin database can inherit the permissions of roles in any other database.

To view role permissions, you can use the following command to query (understand):

// 查询所有角色权限(仅用户自定义角色
db.runCommand({
    
     rolesInfo: 1 })

//查询当前数据库中的某角色的权限
db.runCommand({
    
     rolesInfo: "<rolename>" })
//查询其它数据库中指定的角色权限
db.runCommand({
    
     rolesInfo: {
    
     role: "<rolename>", db: "<database>" } }
//查询多个角色权限
db.runCommand(
{
    
    
rolesInfo: [
"<rolename>",
{
    
     role: "<rolename>", db: "<database>" },
...
]
}
)

Query all role permissions (including built-in roles)

db.runCommand({
    
     rolesInfo: 1, showBuiltinRoles: true }

Common built-in roles:

  • Database user roles: read, readWrite
  • All database user roles: readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, dbAdminAnyDatabase
  • Database management roles: dbAdmin, dbOwner, userAdmin
  • Cluster management roles: clusterAdmin, clusterManager, clusterMonitor, hostManager
  • Backup and restore roles: backup, restore
  • Superuser role: root
  • Internal role: system

Commonly used built-in role descriptions:
insert image description here

2. Single instance environment

The following describes how to enable security authentication for the MongoDB service of a single instance (a MongoDB instance without a replica set or sharding enabled)

2.1 Close the Mongo service

The single-instance security authentication function of mongod can be added directly when the service is built, or it can be added to the previously built service.

There are two ways to stop the service: fast shutdown and standard shutdown, which are described in turn below:
(1) Quick shutdown method, directly kill the process through the system's kill command. After killing, check to avoid killing some.

insert image description here

#通过进程编号关闭节点
kill -2 5865

If it is due to data corruption, you need to do the following:
1) Delete the lock file
rm -f /mongodb/single/data/db/*.lock
(2) Repair data

mongod --repair --dbpath=/mongodb/single/data/db 

(2) Standard closing method:
standard closing method, the data is not easy to make mistakes, but it is troublesome. Use the shutdownServer command in the mongo client to shut down the service. The main operation steps are as follows:

#客户端登录服务,注意,这里通过localhost登录,如果需要远程登录,必须先登录认证才行。
 mongo --port 27017 
 #切换到admin库 
 use admin
 #关闭服务 
 db.shutdownServer()

2.2 Add users and permissions

(1) Configure the server configuration file /mongodb/single/mongod.conf:

systemLog:
  #MongoDB发送所有日志输出的目标指定为文件
  # #The path of the log file to which mongod or mongos should send all diagnostic   logging information
  destination: file
  #mongod或mongos应向其发送所有诊断日志记录信息的日志文件的路径
  path: "/mongodb/single/log/mongod.log"
  #当mongos或mongod实例重新启动时,mongos或mongod会将新条目附加到现有日志文件的末尾。
  logAppend: true
storage:
  #mongod实例存储其数据的目录。storage.dbPath设置仅适用于mongod。
  ##The directory where the mongod instance stores its data.Default Value is "/data/db".
  dbPath: "/mongodb/single/data/db"
  journal:
  #启用或禁用持久性日志以确保数据文件保持有效和可恢复。
    enabled: true
processManagement:
  #启用在后台运行mongos或mongod进程的守护进程模式。
  fork: true
net:
  #服务实例绑定的IP,默认是localhost
  bindIp: localhost,10.0.16.9
  #bindIp
  #绑定的端口,默认是27017
  port: 27017

(2) Start the MongoDB service without authentication (without adding the --auth parameter)

mongod -f /mongodb/single/mongod.conf

(3) Log in with the Mongo client

mongo --host 110.0.16.9 --port 27017

(4) Create two administrator users, one is the super administrator myroot of the system, and the other is the management user myadmin of the admin library:

Switch to the admin library, create the system super user myroot, set the password 123456, and set the role root

use admin
db.createUser({
    
    user:"myroot",pwd:"123456",roles:["root"]})

Create an account myadmin specially used to manage the admin library, which is only used as the management of user permissions

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

insert image description here

View the status of the created users:

db.system.users.find()

insert image description here

delete users

db.dropUser("myadmin")

insert image description here

change Password

db.changeUserPassword("myroot", "123456")

Tips:
1) In this case, two users are created, corresponding to the superman and the role specially used to manage users. In fact, you only need one user. If you have high security requirements to prevent super pipe leakage, do not create a super pipe user.
2) Like other databases (MySQL), the management of permissions is almost the same, and the user and permission information is also saved in the corresponding
table of the database. Mongodb stores all user information in the collection system.users of the admin database, saving user names, passwords
and database information.
3) If no database is specified, the created user with the specified authority is valid on all databases, such as{role:"userAdminAnyDatabase", db:""}

(5) Certification test

#切换到admin
> use admin
#密码输错
> db.auth("myroot","12345")
Error: Authentication failed.
0
#密码正确
> db.auth("myroot","123456")

insert image description here

(6) Create a common user
Create a common user can be added when the authentication is not enabled, or after the authentication is enabled, but after the authentication is enabled, you must use the user who has operated the admin library to log in and authenticate before operating. The bottom layer is to save user information in the collection system.users of the admin database.

Create (switch) the database articledb, a user who has read and write permissions for the articledb database readWrite

use articledb
db.createUser({
    
    user: "bobo", pwd: "123456", roles: [{
    
    role:"readWrite", db:"articledb" }]})

Test whether the account is available

db.auth("bobo","123456)

insert image description here
If authentication is enabled, the logged-in client user must use the role of the admin library, such as the myadmin user with the root role, and then use the myadmin user to create users with other roles.

2.3 Enable authentication on the server

(1) Close the service that has been started

 use admin
 db.shutdownServer()

Conditions for executing the command db.shutdownServer():

  • The shutdown service command must be executed under the admin library.
  • If authentication is not enabled, you must log in from localhost to execute the command to close the service.
  • Non-localhost, through remote login, must be logged in and the logged-in user must have the admin operation authority.

(2) Start the service by enabling authentication

There are two ways to enable authority authentication to start the service: one is the parameter method, and the other is the configuration file method.

Parameter mode, specify the parameter --auth at startup, such as:

mongod -f /mongodb/single/mongod.conf --auth

Configuration file method
Add the following configuration to the mongod.conf configuration file:

security:
  #开启授权认证
  authorization: enabled

After adding this configuration, you can start without adding parameters –auth

2.4 Client connection login

There are two authentication methods for client login when authentication is enabled, one is to log in first and authenticate in the mongo shell; the other is to directly authenticate when logging in.

2.4.1 Connect first and then authenticate

mongo --host 180.76.159.126 --port 27017

After enabling the authentication and then logging in, it is found that the printed logs are relatively small. Relevant operations require authentication: query the users of the system.users collection in the admin library:

use admin
db.system.users.find()

insert image description here
Log in to the super administrator account

db.auth("myroot","123456")
db.system.users.find()

insert image description here
Log out and log in again to query the content of the comment collection in the articledb library

use articledb
db.comment.find()
db.auth("bobo","123")
db.comment.find()

insert image description here
If this error occurs: Too many users are authenticating. This is because two users are logged in consecutively. You need to log out and then log in again
insert image description here

2.4.2 Direct authentication on connection

Perform login authentication and related operations on the admin database:

mongo --host 180.76.159.126 --port 27017 --authenticationDatabase  admin -u myroot -p 123456

Parameter Description:

  • -u : username
  • -p : password
  • --authenticationDatabase : Specifies which library to connect to. When the login is to specify the username and password, the corresponding database must be specified!

Perform login authentication and related operations on the articledb database:

mongo --host 180.76.159.126 --port
27017 --authenticationDatabase articledb -u bobo -p 12345

2.5 Spring Data Mongo connection authentication

To connect to MongoDB server with username and password, you must use
the format 'username:password@hostname/dbname', where 'username' is the username and 'password' is the password.

Configuration example:

spring:
  #数据源配置
  data:
    mongodb:
      #主机地址
      #host: 180.76.159.126
      # 数据库
      #database: articledb
      # 默认端口是27017
      #port: 27017
      #帐号
      #username: bobo
      #密码
      #password: 123456
      #单机有认证的情况下,也使用字符串连接
      uri: mongodb://bobo:[email protected]:27017/articled

3. Replica set environment

For the built mongodb replica set, for security, enable security authentication and log in with the account and password. The configuration of the replica set architecture is as follows:
insert image description here
performing access control on the replica set requires configuration in two aspects:
1) Internal authentication is used between the replica set and each node member of the shared cluster, and key files or x.509 certificates can be used. The key file is relatively simple. This article uses the key file. The official recommendation is that the key file can be used in the test environment, but in the formal environment, the official recommendation is the x.509 certificate. The principle is that when each instance in the cluster connects to each other, it checks whether the contents of the certificates used by each other are the same. Only instances with the same certificate can access each other.

2) When using the client to connect to the mongodb cluster, enable access authorization. For access outside the cluster.
For example , when connecting through a visual client or through code, authorization needs to be enabled.

In keyfile authentication, each mongod instance in the replica set uses the contents of the keyfile as a shared secret, and only
mongod or mongos instances with the correct keyfile can connect to the replica set. The content of the key file must be between 6 and 1024 characters
, and the file owner must have at least read permission on the file in unix/linux systems.

3.1 Shut down the enabled replica set service

The security authentication and service authentication functions of the replica set can be added directly when the replica set is built, or can be added to the previously built replica
set service.

(1) Quick shutdown method
Kill the process directly through the system's kill command.

#通过进程编号关闭节点
kill -2 54410

Kill the arbitrator, replica node, master node in sequence until all members are offline. It is recommended that the master node be killed last to avoid potential rollbacks. After killing, check to avoid killing some

2) Standard shutdown method (the data is not easy to make mistakes, but it is troublesome):
use the shutdownServer command in the mongo client to shut down each service in turn, and the operation command is as follows.

//客户端登录服务,注意,这里通过localhost登录,如果需要远程登录,必须先登录认证才行。
mongo --port 27017
//告知副本集说本机要下线
rs.stepDown()
//#切换到admin库
use admin
//关闭服务
db.shutdownServer()

To shut down the services in the replica set, it is recommended to shut down the arbitration node, replica node, and master node in sequence.

3.2 Add an administrator account through the master node

You only need to add users on the primary node, and the replica set will be automatically synchronized. Before enabling authentication, create a hypervisor user: myroot, password: 123456.

use admin
db.createUser({
    
    user:"myroot",pwd:"123456",roles:["root"]})

For detailed operations, see the related operations of adding users and permissions in a single-instance environment.
Tip: This step can also be done after enabling authentication, but you need to log in through localhost to allow adding users, and user data will be automatically synchronized to the replica set. Subsequent creation of other users can be created using this hypervisor user.

3.3 Create a key file for replica set authentication

Keyfiles can be generated using any method. For example, the following operation uses openssl to generate a password file, then uses chmod to change
the file permissions to give read permission only to the file owner

openssl rand -base64 90 -out ./mongo.keyfile
chmod 400 ./mongo.keyfile
ll mongo.keyfile

Tip:
All replica set nodes must use the same keyfile, which is usually generated on one machine and then copied to other machines, and must
have read permission, otherwise an error will be reported in the future:permissions on /mongodb/replica_sets/myrs_27017/mongo.keyfile are too open

Be sure to ensure that the key file is consistent and the file location is random. However, for the convenience of searching, it is recommended that each machine be placed in a fixed location,
in the same directory as the configuration file.

Copy the file to multiple directories here:

cp mongo.keyfile /mongodb/replica_sets/myrs_27017
cp mongo.keyfile /mongodb/replica_sets/myrs_27018
cp mongo.keyfile /mongodb/replica_sets/myrs_27019

3.4 Modify the configuration file to specify the keyfile

Edit the mongod.conf files of several services separately, and add relevant content:

Configuration file of mongodb/replica_sets/myrs_27017/mongod.conf:

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/replica_sets/myrs_27017/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/replica_sets/myrs_27018/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/replica_sets/myrs_27018/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/replica_sets/myrs_27019/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/replica_sets/myrs_27019/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

3.5 Restart the replica set

If the replica set is open, first shut down each mongod in the replica set, starting from the secondary node. Until all
members of the replica set are offline, including any arbitrators. The primary must be the last member to shut down to avoid potential rollbacks.

#通过进程编号关闭三个节点
kill -2 54410 54361 54257

Start the replica set nodes separately:

mongod -f /mongodb/replica_sets/myrs_27017/mongod.conf
mongod -f /mongodb/replica_sets/myrs_27018/mongod.conf
mongod -f /mongodb/replica_sets/myrs_27019/mongod.conf

Check the process and check whether the three replica set nodes are started successfully

ps -ef |grep mongod

3.6 Add a common account on the master node

First log in with the administrator account and switch to the admin library

use admin

Administrator account authentication

db.auth("myroot","123456")

Switch to the library to be authenticated

use articledb

add common user

db.createUser({
    
    user: "bobo", pwd: "123456", roles: ["readWrite"]})

Reconnect, log in again as a common user bobo, and check the data.

3.7 Spring Data Mongo connection authentication

To connect to MongoDB server with username and password, you must use the format 'username:password@hostname/dbname', where 'username' is the username and 'password' is the password.

Example:

spring:
#数据源配置
data:
mongodb:
#副本集有认证的情况下,字符串连接
uri:
mongodb://bobo:[email protected]:27017,180.76.159.126:27018,180.76.159.126:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs

4. Sharded cluster environment

4.1 Shut down the enabled replica set service

The server environment and architecture of the slice cluster are relatively complex. It is recommended to directly add security authentication and authentication between servers when building a slice cluster. If there is data before, you can first backup the previous data and restore it back.

There are two ways to stop a service: fast shutdown and standard shutdown.
(1) Quick shutdown
The method of directly killing the process through the system's kill command to quickly shut down the Mongo service is fast and simple, and the data may be wrong.Kill the mongos routing node, configure the replica set service, and fragment the replica set service in sequence, starting from the secondary node. until all members are offline. When killing a replica set, it is recommended to kill the arbitrator first, then the replica nodes, and finally the master node to avoid potential rollbacks. After killing, check to avoid killing some. The command is as follows:

ps aux|grep mongo
#通过进程编号关闭节点
kill -2 54410

(2) Standard shutdown method
Shut down each service in turn through the shutdownServer command in the mongo client.

To shut down the services in the replica set of the shard server, it is recommended to shut down the arbitration node, the replica node, and the master node in sequence. The main operation steps are as follows:

//客户端登录服务,注意,这里通过localhost登录,如果需要远程登录,必须先登录认证才行。
mongo --port 27018
//告知副本集说本机要下线
rs.stepDown()
//#切换到admin库
use admin
//关闭服务
db.shutdownServer()

To close the service of the configuration server replica set, it is recommended to shut down the replica node and the master node in sequence. The main operation steps are as follows:

//客户端登录服务,注意,这里通过localhost登录,如果需要远程登录,必须先登录认证才行。
mongo --port 27019
//告知副本集说本机要下线
rs.stepDown()
//#切换到admin库
use admin
//关闭服务
db.shutdownServer()

To shut down the service of the routing server, it is recommended to shut down the two routing nodes in turn. The main operation steps are as follows:

/客户端登录服务,注意,这里通过localhost登录,如果需要远程登录,必须先登录认证才行。
mongo --port 27017
//告知副本集说本机要下线
rs.stepDown()
//#切换到admin库
use admin
//关闭服务
db.shutdownServer()

4.2 Create a key file for replica set authentication

(1) Step 1: Generate a key file into the current folder.

Keyfiles can be generated using any method. For example, the following operation uses openssl to generate a password file, then uses chmod to change
the file permissions to give read permission only to the file owner

openssl rand -base64 90 -out ./mongo.keyfile
chmod 400 ./mongo.keyfile
ll mongo.keyfil

Tip:
All replica set nodes must use the same keyfile, which is usually generated on one machine and then copied to other machines, and must
have read permission, otherwise an error will be reported in the future:permissions on /mongodb/replica_sets/myrs_27017/mongo.keyfile are too open

Be sure to ensure that the key file is consistent and the file location is random. However, for the convenience of searching, it is recommended that each machine be placed in a fixed location, in the same directory as the configuration file.

Copy the file to multiple directories here:

echo '/mongodb/sharded_cluster/myshardrs01_27018/mongo.keyfile
/mongodb/sharded_cluster/myshardrs01_27118/mongo.keyfile
/mongodb/sharded_cluster/myshardrs01_27218/mongo.keyfile
/mongodb/sharded_cluster/myshardrs02_27318/mongo.keyfile
/mongodb/sharded_cluster/myshardrs02_27418/mongo.keyfile
/mongodb/sharded_cluster/myshardrs02_27518/mongo.keyfile
/mongodb/sharded_cluster/myconfigrs_27019/mongo.keyfile
/mongodb/sharded_cluster/myconfigrs_27119/mongo.keyfile
/mongodb/sharded_cluster/myconfigrs_27219/mongo.keyfile
/mongodb/sharded_cluster/mymongos_27017/mongo.keyfile
/mongodb/sharded_cluster/mymongos_27117/mongo.keyfile' | xargs -n 1 cp -v
/root/mongo.keyfile

4.3 Modify the configuration file to specify the keyfile

Edit the mongod.conf files of several services separately, and add relevant content:

/mongodb/sharded_cluster/myshardrs01_27018/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myshardrs01_27018/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/myshardrs01_27118/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myshardrs01_27118/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/myshardrs01_27218/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myshardrs01_27218/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/myshardrs02_27318/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myshardrs02_27318/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/myshardrs02_27418/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myshardrs02_27418/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/myshardrs02_27518/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myshardrs02_27518/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/myconfigrs_27019/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myconfigrs_27019/mon/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/myconfigrs_27119/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myconfigrs_27119/mon/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/myconfigrs_27219/mongod.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/myconfigrs_27219/mon/mongo.keyfile
  #开启认证方式运行
  authorization: enabled

/mongodb/sharded_cluster/mymongos_27017/mongos.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/mymongos_27017/mon/mongo.keyfile

/mongodb/sharded_cluster/mymongos_27117/mongos.conf

security:
  #KeyFile鉴权文件
  keyFile: /mongodb/sharded_cluster/mymongos_27117/mon/mongo.keyfile

Mongos has less authorization: enabled configuration than mongod. The reason is that the security authentication of the replica set plus fragmentation needs to be configured in two aspects. The internal authentication is used between the nodes of the replica set for the communication of each internal mongo instance. Only the same keyfile can access each other. So open keyFile:/mongodb/sharded_cluster/mymongos_27117/mongo.keyfile.

However, for all mongods, it is the real shards that store data. Mongos only does routing and does not save data. So all mongods enable authorization:enabled to access data. In this way, the user can only access the data if the account password is correct.

4.4 Restart the node

The configuration node, fragmentation node, and routing node must be started in sequence:

#启动配置节点
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myconfigrs_27019/mongod.conf
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myconfigrs_27119/mongod.conf
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myconfigrs_27219/mongod.conf
#启动分片节点
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myshardrs01_27018/mongod.conf
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myshardrs01_27118/mongod.conf
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myshardrs01_27218/mongod.conf
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myshardrs02_27318/mongod.conf
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myshardrs02_27418/mongod.conf
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/myshardrs02_27518/mongod.conf
#启动路由节点
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/mymongos_27017/mongos.conf
/usr/local/mongodb/bin/mongod -f /mongodb/sharded_cluster/mymongos_27117/mongos.conf

Note: There is a very special case here, which is the boot sequence. Start the configuration node first, then the shard node, and finally the routing node.

4.5 Create an account and authenticate

Client mongo, log in to any mongos route through localhost

/usr/local/mongodb/bin/mongo --port 27017

Users can only be added under admin. Create an administrator account:

use admin
db.createUser({
    
    user:"myroot",pwd:"123456",roles:["root"]})

Create an account with normal permissions:

 use admin
 db.auth("myroot","123456")
 use articledb
 db.createUser({
    
    user: "bobo", pwd: "123456", roles: [{
    
     role: "readWrite",db:"articledb"}]}
db.auth("bobo","123456")

The account information added through mongos will only be saved in the service of the configuration node, and the specific data node will not save the account information. Therefore, the
account information in the shard does not involve synchronization issues

The mongo client logs in to the mongos route, and logs in with an administrator account to view the fragmentation:

use admin
db.auth("myroot","123456")
 sh.status()

Exit the connection, reconnect to the service, and use the normal authority account to access the data:

mongo --host 180.76.159.126 --port 27017
db.auth("bobo","123456")
show collections
db.comment.count()

4.6 Spring Data Mongo connection authentication

To connect to MongoDB server with username and password, you must use the format 'username:password@hostname/dbname', where 'username' is the username and 'password' is the password.

Goal: Use the user bobo to connect to the MongoDB service with the password 123456. application.yml example:

spring:
  #数据源配置
  data:
    mongodb:
    # 分片集群有认证的情况下,字符串连接
     uri:
    mongodb://bobo:[email protected]:27017,180.76.159.126:27117/articledb

Guess you like

Origin blog.csdn.net/huangjhai/article/details/124539482