我想为我的MongoDB实例设置用户名和密码身份验证,以便任何远程访问都将要求提供用户名和密码。我尝试了MongoDB站点的教程,并做了以下工作:

use admin
db.addUser('theadmin', '12345');
db.auth('theadmin','12345');

在那之后,我退出了,再次跑了mongo。而且我不需要密码就能进入。即使我远程连接到数据库,也不会提示我输入用户名和密码。


这是我最终使用的解决方案

1) At the mongo command line, set the administrator:

    use admin;
    db.addUser('admin','123456');

2) Shutdown the server and exit

    db.shutdownServer();
    exit

3) Restart mongod with --auth

  $ sudo ./mongodb/bin/mongod --auth --dbpath /mnt/db/

4) Run mongo again in 2 ways:

   i) run mongo first then login:

        $ ./mongodb/bin/mongo localhost:27017
        use admin
        db.auth('admin','123456');

  ii) run & login to mongo in command line.

        $ ./mongodb/bin/mongo localhost:27017/admin -u admin -p 123456

用户名和密码将以同样的方式工作在mongodb和mongoexport。


当前回答

我已经在6.0版中做到了这一点 如何设置数据库的用户名和密码;

安装MongoDB 6.0或更高版本 使用compass在MongoDB中创建数据库(不管名字是什么)

安装MongoDB Shell https://www.mongodb.com/try/download/shell

打开cmd

cd C:\Program Files\mongosh

mongosh“mongodb: / / localhost: 27017”

使用#您的数据库名称#

db。createUser({user: "xxx", pwd: "xxx", roles: [{role: "readWrite", db: "xxx"}]})

其他回答

首先在终端上运行mongoDB

mongod

现在运行mongo shell use下面的命令

    use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

重新启动带有访问控制的MongoDB实例。

mongod --auth

现在从命令行使用验证自己

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

我读过

https://docs.mongodb.com/manual/tutorial/enable-authentication/

在设置用户后,需要使用——auth选项启动mongod。

来自MongoDB站点:

运行数据库(mongod进程),并启用——auth选项 安全。您必须在之前向admin db中添加了一个用户 使用——auth启动服务器,或从 主机接口。

MongoDB身份验证

按顺序执行以下步骤

该任务指导管理员通过CLI创建用户

use admin
db.createUser(
  {
    user: "admin",
    pwd: "admin123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

启用身份验证,你怎么做取决于你的操作系统,如果你使用的是windows,你可以简单地mongod——auth,如果是linux,你可以编辑/etc/mongod.conf文件来增加安全性。授权:启用后重新启动服务 通过cli mongo连接-u "admin" -p "admin123"——authenticationDatabase "admin"就是这样

你可以查看这篇文章了解更多细节,并学习使用猫鼬连接它。

我已经在6.0版中做到了这一点 如何设置数据库的用户名和密码;

安装MongoDB 6.0或更高版本 使用compass在MongoDB中创建数据库(不管名字是什么)

安装MongoDB Shell https://www.mongodb.com/try/download/shell

打开cmd

cd C:\Program Files\mongosh

mongosh“mongodb: / / localhost: 27017”

使用#您的数据库名称#

db。createUser({user: "xxx", pwd: "xxx", roles: [{role: "readWrite", db: "xxx"}]})

为特定数据库创建用户和密码以确保数据库访问安全:

use dbName

db.createUser(
   {
     user: "dbUser",
     pwd: "dbPassword",
     roles: [ "readWrite", "dbAdmin" ]
   }
)