- 安全 >
- Security Tutorials >
- Access Control Tutorials >
- Enable Client Access Control
Enable Client Access Control¶
概述¶
Enabling access control on a MongoDB instance restricts access to the instance by requiring that users identify themselves when connecting. In this procedure, you enable access control and then create the instance’s first user, which must be a user administrator. The user administrator grants further access to the instance by creating additional users.
Considerations¶
If you create the user administrator before enabling access control, MongoDB disables the localhost exception. In that case, you must use the “Enable Authentication after Creating the User Administrator” procedure to enable access control.
This procedure uses the localhost exception to allow you to create the first user after enabling authentication. See 本地主机例外 and 认证 for more information.
Procedure¶
Start the MongoDB instance with authentication enabled.¶
Start the mongod or mongos instance with the authorization or keyFile setting. Use authorization on a standalone instance. Use keyFile on an instance in a replica set or sharded cluster.
For example, to start a mongod with authentication enabled and a key file stored in /private/var, first set the following option in the mongod‘s configuration file:
security:
keyFile: /private/var/key.pem
Then start the mongod and specify the config file. For example:
mongod --config /etc/mongodb/mongodb.conf
After you enable authentication, only the user administrator can connect to the MongoDB instance. The user administrator must log in and grant further access to the instance by creating additional users.
Connect to the MongoDB instance via the localhost exception.¶
Connect to the MongoDB instance from a client running on the same system. This access is made possible by the localhost exception.
Create the system user administrator.¶
Add the user with the userAdminAnyDatabase role, and only that role.
The following example creates the user siteUserAdmin user on the admin database:
use admin
db.createUser(
{
user: "siteUserAdmin",
pwd: "password",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
After you create the user administrator, the localhost exception is no longer available.
Create additional users.¶
Login in with the user administrator’s credentials and create additional users. See Add a User to a Database.
Next Steps¶
If you need to disable access control for any reason, restart the process without the authorization or keyFile setting.