Deploy Replica Set With Keyfile Authentication使用密钥文件身份验证部署副本集

On this page本页内容

Overview概述

Enforcing access control on a replica set requires configuring:副本集实施访问控制需要配置:

For this tutorial, each member of the replica set uses the same internal authentication mechanism and settings.对于本教程,副本集的每个成员都使用相同的内部身份验证机制和设置。

Enforcing internal authentication also enforces user access control. 强制内部身份验证还强制用户访问控制。To connect to the replica set, clients like mongosh need to use a user account. 要连接到副本集,像mongosh这样的客户端需要使用用户帐户See Users and Authentication Mechanisms.请参阅用户和身份验证机制

Cloud Manager and Ops Manager云管理器和运营管理器

If you are currently using or are planning to use Cloud Manager or Ops Manager, see the Cloud Manager manual or the Ops Manager manual for enforcing access control.如果您当前正在使用或计划使用云管理器或Ops管理器,请参阅云管理器手册Ops管理器手册以强制执行访问控制。

Considerations注意事项

Important重要

To avoid configuration updates due to IP address changes, use DNS hostnames instead of IP addresses. 为了避免由于IP地址更改而进行配置更新,请使用DNS主机名而不是IP地址。It is particularly important to use a DNS hostname instead of an IP address when configuring replica set members or sharded cluster members.在配置副本集成员或分片群集成员时,使用DNS主机名而不是IP地址尤为重要。

Use hostnames instead of IP addresses to configure clusters across a split network horizon. 使用主机名而不是IP地址来跨拆分的网络范围配置群集。Starting in MongDB 5.0, nodes that are only configured with an IP address will fail startup validation and will not start.从MongDB 5.0开始,仅配置IP地址的节点将无法通过启动验证,无法启动。

IP BindingIP绑定

Changed in version 3.6.在版本3.6中更改

Starting in MongoDB 3.6, mongod and mongos bind to localhost by default. 从MongoDB 3.6开始,mongodmongos默认绑定到localhost。If the members of your deployment are run on different hosts or if you wish remote clients to connect to your deployment, you must specify --bind_ip or net.bindIp. 如果部署的成员在不同的主机上运行,或者希望远程客户端连接到部署,则必须指定--bind_ipnet.bindIpFor more information, see Localhost Binding Compatibility Changes.有关详细信息,请参阅Localhost绑定兼容性更改

Operating System操作系统

This tutorial primarily refers to the mongod process. 本教程主要介绍mongod过程。Windows users should use the exe program instead.Windows用户应该改用exe程序。

Keyfile Security密钥文件安全性

Keyfiles are bare-minimum forms of security and are best suited for testing or development environments. 密钥文件是最低限度的安全形式,最适合测试或开发环境。For production environments we recommend using x.509 certificates.对于生产环境,我们建议使用x.509证书

Users and Authentication Mechanisms用户和身份验证机制

This tutorial covers creating the minimum number of administrative users on the admin database only. For the user authentication, the tutorial uses the default SCRAM authentication mechanism. Challenge-response security mechanisms are best suited for testing or development environments. For production environments, we recommend using x.509 certificates or LDAP Proxy Authentication(available for MongoDB Enterprise only) or Kerberos Authentication(available for MongoDB Enterprise only).

For details on creating users for specific authentication mechanism, refer to the specific authentication mechanism pages.有关为特定验证机制创建用户的详细信息,请参阅特定验证机制页面。

See ➤ Configure Role-Based Access Control for best practices for user creation and management.有关用户创建和管理的最佳实践,请参阅➤ 配置基于角色的访问控制

Deploy New Replica Set with Keyfile Access Control使用密钥文件访问控制部署新副本集

Important重要

To avoid configuration updates due to IP address changes, use DNS hostnames instead of IP addresses. 为了避免由于IP地址更改而进行配置更新,请使用DNS主机名而不是IP地址。It is particularly important to use a DNS hostname instead of an IP address when configuring replica set members or sharded cluster members.在配置副本集成员或分片群集成员时,使用DNS主机名而不是IP地址尤为重要。

Use hostnames instead of IP addresses to configure clusters across a split network horizon. 使用主机名而不是IP地址来跨拆分的网络范围配置群集。Starting in MongDB 5.0, nodes that are only configured with an IP address will fail startup validation and will not start.从MongDB 5.0开始,仅配置IP地址的节点将无法通过启动验证,无法启动。

1

Create a keyfile.创建密钥文件。

With keyfile authentication, each mongod instances in the replica set uses the contents of the keyfile as the shared password for authenticating other members in the deployment. Only mongod instances with the correct keyfile can join the replica set.

Note注意

Starting in MongoDB 4.2, keyfiles for internal membership authentication use YAML format to allow for multiple keys in a keyfile. The YAML format accepts content of:

  • a single key string (same as in earlier versions),
  • multiple key strings (each string must be enclosed in quotes), or
  • sequence of key strings.

The YAML format is compatible with the existing single-key keyfiles that use the text file format.YAML格式与使用文本文件格式的现有单键密钥文件兼容。

A key's length must be between 6 and 1024 characters and may only contain characters in the base64 set. 密钥的长度必须介于6到1024个字符之间,并且只能包含base64集合中的字符。All members of the replica set must share at least one common key.副本集的所有成员必须至少共享一个公用密钥。

Note注意

On UNIX systems, the keyfile must not have group or world permissions. 在UNIX系统上,密钥文件不能具有组或世界权限。On Windows systems, keyfile permissions are not checked.在Windows系统上,不检查密钥文件权限。

You can generate a keyfile using any method you choose. 可以使用您选择的任何方法生成密钥文件。For example, the following operation uses openssl to generate a complex pseudo-random 1024 character string to use as a shared password. 例如,以下操作使用openssl生成一个复杂的伪随机1024字符串,用作共享密码。It then uses chmod to change file permissions to provide read permissions for the file owner only:然后,它使用chmod更改文件权限,仅为文件所有者提供读取权限:

openssl rand -base64 756 > <path-to-keyfile>
chmod 400 <path-to-keyfile>

See Keyfiles for additional details and requirements for using keyfiles.有关使用密钥文件的其他详细信息和要求,请参阅密钥文件

2

Copy the keyfile to each replica set member.将密钥文件复制到每个副本集成员。

Copy the keyfile to each server hosting the replica set members. 将密钥文件复制到承载副本集成员的每个服务器。Ensure that the user running the mongod instances is the owner of the file and can access the keyfile.确保运行mongod实例的用户是文件的所有者,并且可以访问密钥文件。

Avoid storing the keyfile on storage mediums that can be easily disconnected from the hardware hosting the mongod instances, such as a USB drive or a network attached storage device.避免将密钥文件存储在存储介质上,这些介质可以很容易地与托管mongod实例的硬件断开连接,例如USB驱动器或网络连接的存储设备。

3

Start each member of the replica set with access control enabled.在启用访问控制的情况下启动副本集的每个成员。

For each member in the replica set, start the mongod with either the security.keyFile configuration file setting or the --keyFile command-line option. Running mongod with the --keyFile command-line option or the security.keyFile configuration file setting enforces both Internal/Membership Authentication and Role-Based Access Control.

Configuration File配置文件

If using a configuration file, set如果使用配置文件,请设置

Include additional options as required for your configuration. For instance, if you wish remote clients to connect to your deployment or your deployment members are run on different hosts, specify the net.bindIp setting. For more information, see Localhost Binding Compatibility Changes.

security:
  keyFile: <path-to-keyfile>
replication:
  replSetName: <replicaSetName>
net:
   bindIp: localhost,<hostname(s)|ip address(es)>

Start the mongod using the configuration file:

mongod --config <path-to-config-file>

For more information on the configuration file, see configuration options.有关配置文件的更多信息,请参阅配置选项

Command Line命令行

If using the command line options, start the mongod with the following options:如果使用命令行选项,请使用以下选项启动mongod

  • --keyFile set to the keyfile's path, and设置为密钥文件的路径,并且
  • --replSet set to the replica set name.设置为副本集名称。

Include additional options as required for your configuration. 包括配置所需的其他选项。For instance, if you wish remote clients to connect to your deployment or your deployment members are run on different hosts, specify the --bind_ip. 例如,如果希望远程客户端连接到部署,或者部署成员在不同的主机上运行,请指定--bind_ipFor more information, see Localhost Binding Compatibility Changes.有关详细信息,请参阅Localhost绑定兼容性更改

mongod --keyFile <path-to-keyfile> --replSet <replicaSetName> --bind_ip localhost,<hostname(s)|ip address(es)>
Important重要

To avoid configuration updates due to IP address changes, use DNS hostnames instead of IP addresses. It is particularly important to use a DNS hostname instead of an IP address when configuring replica set members or sharded cluster members.

Use hostnames instead of IP addresses to configure clusters across a split network horizon. Starting in MongDB 5.0, nodes that are only configured with an IP address will fail startup validation and will not start.

For more information on command-line options, see the mongod reference page.

4

Connect to a member of the replica set over the localhost interface.

Connect mongosh to one of the mongod instances over the localhost interface. You must run mongosh on the same physical machine as the mongod instance.

The localhost interface is only available since no users have been created for the deployment. The localhost interface closes after the creation of the first user.

5

Initiate the replica set.

From mongosh, run the rs.initiate() method.

rs.initiate() can take an optional replica set configuration document. In the replica set configuration document, include:

  • The _id field set to the replica set name specified in either the replication.replSetName or the --replSet option.
  • The members array with a document per each member of the replica set.

The following example initates a three member replica set.

Important重要

Run rs.initiate() on just one and only onemongod instance for the replica set.

Important重要

To avoid configuration updates due to IP address changes, use DNS hostnames instead of IP addresses. It is particularly important to use a DNS hostname instead of an IP address when configuring replica set members or sharded cluster members.

Use hostnames instead of IP addresses to configure clusters across a split network horizon. Starting in MongDB 5.0, nodes that are only configured with an IP address will fail startup validation and will not start.

rs.initiate(
  {
    _id : "myReplSet",
    members: [
      { _id : 0, host : "mongo1.example.net:27017" },
      { _id : 1, host : "mongo2.example.net:27017" },
      { _id : 2, host : "mongo3.example.net:27017" }
    ]
  }
)

rs.initiate() triggers an election and elects one of the members to be the primary.

Connect to the primary before continuing. Use rs.status() to locate the primary member.

6

Create the user administrator.

Important重要

After you create the first user, the localhost exception is no longer available.

The first user must have privileges to create other users, such as a user with the userAdminAnyDatabase. This ensures that you can create additional users after the Localhost Exception closes.

If at least one user does not have privileges to create users, once the localhost exception closes you may be unable to create or modify users with new privileges, and therefore unable to access necessary operations.

Add a user using the db.createUser() method. The user should have at minimum the userAdminAnyDatabase role on the admin database.

You must be connected to the primary to create users.

The following example creates the user fred with the userAdminAnyDatabase role on the admin database.

Important重要

Passwords should be random, long, and complex to ensure system security and to prevent or delay malicious access.

Tip提示

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.

admin = db.getSiblingDB("admin")
admin.createUser(
  {
    user: "fred",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

Enter the password when prompted. See Database User Roles for a full list of built-in roles and related to database administration operations.

7

Authenticate as the user administrator.

Authenticate to the admin database.

In mongosh, use db.auth() to authenticate. For example, the following authenticate as the user administrator fred:

Tip提示

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.

db.getSiblingDB("admin").auth("fred", passwordPrompt()) // or cleartext password

Alternatively, connect a new mongosh instance to the primary replica set member using the -u <username>, -p <password>, and the --authenticationDatabase parameters.

mongosh -u "fred" -p  --authenticationDatabase "admin"

If you do not specify the password to the -p command-line option, mongosh prompts for the password.

8

Create the cluster administrator.

The clusterAdmin role grants access to replication operations, such as configuring the replica set.

Create a cluster administrator user and assign the clusterAdmin role in the admin database:

Tip提示

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.

db.getSiblingDB("admin").createUser(
  {
    "user" : "ravi",
    "pwd" : passwordPrompt(),
     // or cleartext password
    roles: [ { "role" : "clusterAdmin", "db" : "admin" } ]
  }
)

Enter the password when prompted.

See Cluster Administration Roles for a full list of built-in roles related to replica set and sharded cluster operations.

9

Create additional users (Optional).

Create users to allow clients to connect and interact with the replica set. See Database User Roles for basic built-in roles to use in creating read-only and read-write users.

You may also want additional administrative users. For more information on users, see Users.

x.509 Internal Authentication

For details on using x.509 for internal authentication, see Use x.509 Certificate for Membership Authentication.

To upgrade from keyfile internal authentication to x.509 internal authentication, see Upgrade from Keyfile Authentication to x.509 Authentication.

←  Internal/Membership AuthenticationUpdate Replica Set to Keyfile Authentication →