Database Manual / Self-Managed Deployments / Security / Authentication / Users

Authenticate a User with Self-Managed Deployments使用自我管理部署对用户进行身份验证

To authenticate as a user, you must provide a username, password, and the authentication database associated with that user.要作为用户进行身份验证,您必须提供用户名、密码和与该用户关联的身份验证数据库

Important

It is not possible to switch between users in the same mongosh session. Authenticating as a different user means the session has the privileges of both authenticated users. 无法在同一mongosh会话中的用户之间切换。作为不同用户进行身份验证意味着会话具有两个经过身份验证的用户的权限。To switch between users exit and relaunch mongosh.要在用户之间切换,请退出并重新启动mongosh

Using mongosh, you can:使用mongosh,您可以:

Authenticate during Connection连接期间进行身份验证

Start mongosh with the -u <username>, -p, and the --authenticationDatabase <database> command line options:使用-u <username>-p--authenticationDatabase <database>命令行选项启动mongosh

mongosh --port 27017  --authenticationDatabase \
"admin" -u "myUserAdmin" -p

Enter your password when prompted.出现提示时输入密码。

Authenticate after Connection连接后进行身份验证

Using mongosh, connect to the mongod or mongos instance:使用mongosh连接到mongodmongos实例:

mongosh --port 27017

In mongosh, switch to the authentication database (in this case, admin), and use the db.auth(<username>, <pwd>) method or the authenticate command to authenticate against the authentication database:mongosh中,切换到身份验证数据库(在本例中为admin),并使用db.auth(<username>, <pwd>)方法或authenticate命令对身份验证数据库进行身份验证:

use admin
db.auth("myUserAdmin", passwordPrompt()) // or cleartext password

Tip

The passwordPrompt() method prompts you to enter the password. passwordPrompt()方法提示您输入密码。You can also specify your password directly as a string. 您还可以直接将密码指定为字符串。We recommend to use the passwordPrompt() method to avoid the password being visible on your screen and potentially leaking the password to your shell history.我们建议使用passwordPrompt()方法,以避免密码在屏幕上可见,并可能将密码泄露到shell历史记录中。

Enter the password when prompted.出现提示时输入密码。

For examples using a MongoDB driver, see the driver documentation.有关使用MongoDB驱动程序的示例,请参阅驱动程序文档