且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用用户名和密码保护 MongoDB

更新时间:2022-10-15 16:03:44

在设置用户后,您需要使用 --auth 选项启动 mongod.>

来自 MongoDB 站点:

使用 --auth 选项运行数据库(mongod 进程)以启用安全.您必须之前已将用户添加到管理数据库使用 --auth 启动服务器,或者添加第一个用户本地主机接口.

MongoDB 认证

I want to set up user name & password authentication for my MongoDB instance, so that any remote access will ask for the user name & password. I tried the tutorial from the MongoDB site and did following:

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

After that, I exited and ran mongo again. And I don't need password to access it. Even if I connect to the database remotely, I am not prompted for user name & password.


UPDATE Here is the solution I ended up using

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

The username & password will work the same way for mongodump and mongoexport.

You need to start mongod with the --auth option after setting up the user.

From the MongoDB Site:

Run the database (mongod process) with the --auth option to enable security. You must either have added a user to the admin db before starting the server with --auth, or add the first user from the localhost interface.

MongoDB Authentication