441

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.

Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
murvinlai
  • 48,919
  • 52
  • 129
  • 177

20 Answers20

140

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

Prashant Pokhriyal
  • 3,727
  • 4
  • 28
  • 40
Alexandru Petrescu
  • 3,449
  • 2
  • 23
  • 23
  • 1
    I have tried that and followed the example. now.. i can set it after I restart the server with --auth. However, when I try to login (./mongo -u theadmin -p 12345 ) I fail. I can't login. – murvinlai Feb 03 '11 at 00:10
  • If after did that you cannot connect, it's because you are trying to connect on the `admin` db, use another db and try again. Only a userAdmin(AnyDatabase) can connect on `admin`. – Vadorequest Feb 07 '14 at 22:51
135

Wow so many complicated/confusing answers here.

This is as of v3.4.

Short answer.

  1. Start MongoDB without access control (/data/db or where your db is).

    mongod --dbpath /data/db
    
  2. Connect to the instance.

    mongo
    
  3. Create the user.

    use some_db
    db.createUser(
      {
        user: "myNormalUser",
        pwd: "xyz123",
        roles: [ { role: "readWrite", db: "some_db" },
                 { role: "read", db: "some_other_db" } ]
      }
    )
    
  4. Stop the MongoDB instance and start it again with access control.

    mongod --auth --dbpath /data/db
    
  5. Connect and authenticate as the user.

    use some_db
    db.auth("myNormalUser", "xyz123")
    db.foo.insert({x:1})
    use some_other_db
    db.foo.find({})
    

Long answer: Read this if you want to properly understand.

It's really simple. I'll dumb the following down https://docs.mongodb.com/manual/tutorial/enable-authentication/

If you want to learn more about what the roles actually do read more here: https://docs.mongodb.com/manual/reference/built-in-roles/

  1. Start MongoDB without access control.

    mongod --dbpath /data/db
    
  2. Connect to the instance.

    mongo
    
  3. Create the user administrator. The following creates a user administrator in the admin authentication database. The user is a dbOwner over the some_db database and NOT over the admin database, this is important to remember.

    use admin
    db.createUser(
      {
        user: "myDbOwner",
        pwd: "abc123",
        roles: [ { role: "dbOwner", db: "some_db" } ]
      }
    )
    

Or if you want to create an admin which is admin over any database:

   use admin
   db.createUser(
     {
       user: "myUserAdmin",
       pwd: "abc123",
       roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
     }
   )
  1. Stop the MongoDB instance and start it again with access control.

    mongod --auth --dbpath /data/db
    
  2. Connect and authenticate as the user administrator towards the admin authentication database, NOT towards the some_db authentication database. The user administrator was created in the admin authentication database, the user does not exist in the some_db authentication database.

    use admin
    db.auth("myDbOwner", "abc123")
    

You are now authenticated as a dbOwner over the some_db database. So now if you wish to read/write/do stuff directly towards the some_db database you can change to it.

use some_db
//...do stuff like db.foo.insert({x:1})
// remember that the user administrator had dbOwner rights so the user may write/read, if you create a user with userAdmin they will not be able to read/write for example.

More on roles: https://docs.mongodb.com/manual/reference/built-in-roles/

If you wish to make additional users which aren't user administrators and which are just normal users continue reading below.

  1. Create a normal user. This user will be created in the some_db authentication database down below.

    use some_db
    db.createUser(
      {
        user: "myNormalUser",
        pwd: "xyz123",
        roles: [ { role: "readWrite", db: "some_db" },
                 { role: "read", db: "some_other_db" } ]
      }
    )
    
  2. Exit the mongo shell, re-connect, authenticate as the user.

    use some_db
    db.auth("myNormalUser", "xyz123")
    db.foo.insert({x:1})
    use some_other_db
    db.foo.find({})
    

Last but not least due to users not reading the commands I posted correctly regarding the --auth flag, you can set this value in the configuration file for mongoDB if you do not wish to set it as a flag.

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • 2
    Finally I got an idea what is really happening. – mestarted Jun 20 '17 at 17:36
  • https://stackoverflow.com/questions/41615574/mongodb-server-has-startup-warnings-access-control-is-not-enabled-for-the-dat/42926515#42926515 – basickarl Jun 26 '17 at 07:39
  • 3
    I find myself wishing accepted answers could get refreshed on SO. This is the most relevant solution as of July 2017. – 4Z4T4R Jul 17 '17 at 15:51
  • 1
    **Please update your answer!** I don't know from where you got *userAdminAnyDatabase* from but it doesn't work. The role is *root* for admin access over all the dbs. – Aakash Verma Nov 15 '17 at 23:26
  • 1
    @AakashVerma https://docs.mongodb.com/manual/reference/built-in-roles/#userAdminAnyDatabase ;) Also NEVER USE ROOT unless for development purposes where you know you cannot be compromised! (tbh just never use root lol) – basickarl Nov 16 '17 at 09:42
  • I don't understand why you need `/data/db`. The dbpath isn't `dbPath: /var/lib/mongodb` ? – John Aug 22 '18 at 09:40
  • @John You are correct, dbpath can be whatever you like, aslong as it is pointing towards your db! (in this example I had my db at /data/db) – basickarl Mar 07 '19 at 13:18
  • Our server just got hacked cause the authentication flag was missing in the config, not on your answer. – Oliver Dixon Dec 25 '20 at 11:55
  • @OliverDixon I'm sorry to hear that. If you look at my answer the `--auth` flag is included when starting the mongoDB process, so I did include it. Yes this flag can also be set in the configuration, whichever one suits your needs. – basickarl Jan 21 '22 at 14:45
  • And for anyone wondering, if you see `mongosh` in the docs, that because it is the new mongo db shell. – Zach Aug 21 '23 at 13:05
72

First, un-comment the line that starts with #auth=true in your mongod configuration file (default path /etc/mongod.conf). This will enable authentication for mongodb.

Then, restart mongodb : sudo service mongod restart

CoderUni
  • 5,474
  • 7
  • 26
  • 58
Shnkc
  • 2,108
  • 1
  • 27
  • 35
  • 14
    default path is `/etc/mongod.conf` not `/etc/mongo.conf` – Mithril Sep 07 '15 at 06:58
  • 2
    or, firstly uncomment, then restart :))) – GioMac Mar 09 '16 at 13:24
  • 2
    Update: Now restart service with : sudo service mongodb restart – sharafjaffri Oct 24 '16 at 19:32
  • config file location and name is as: /etc/mongodb.conf – HGMamaci May 01 '20 at 21:53
  • 1
    In the config file its `authorization: enabled` for version 4.4. See [Mongodb authentication](https://docs.mongodb.com/manual/tutorial/enable-authentication/) paragraph **4 Re-start the MongoDB instance with access control** Be also sure to uncomment the `#security:`. **Example**: `security: authorization: enabled` – Jan Mar 15 '21 at 09:32
56

This answer is for Mongo 3.2.1 Reference

Terminal 1:

$ mongod --auth

Terminal 2:

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

if you want to add without roles (optional):

db.createUser({user:"admin_name", pwd:"1234", roles:[]})

to check if authenticated or not:

db.auth("admin_name", "1234")

it should give you:

1

else :

Error: Authentication failed.
0
 
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Sdembla
  • 1,629
  • 13
  • 13
28

Here is a javascript code to add users.

  1. Start mongod with --auth = true

  2. Access admin database from mongo shell and pass the javascript file.

    mongo admin "Filename.js"

    "Filename.js"

    // Adding admin user
    db.addUser("admin_username", " admin_password");
    // Authenticate admin user
    db.auth("admin_username ", " admin_password ");
    // use  database code from java script
    db = db.getSiblingDB("newDatabase");
    // Adding newDatabase database user  
    db.addUser("database_username ", " database_ password ");
    
  3. Now user addition is complete, we can verify accessing the database from mongo shell

Camilo Martin
  • 37,236
  • 20
  • 111
  • 154
Bharadvaj
  • 281
  • 3
  • 3
27

https://docs.mongodb.com/manual/reference/configuration-options/#security.authorization

Edit the mongo settings file;

sudo nano /etc/mongod.conf

Add the line:

security.authorization : enabled

Restart the service

sudo service mongod restart

Regards

ali ozkara
  • 5,425
  • 2
  • 27
  • 24
13

You could change /etc/mongod.conf.

Before

#security:

After

security:
    authorization: "enabled"

Then sudo service mongod restart

Prashant Sharma
  • 807
  • 12
  • 17
12

First run mongoDB on terminal using

mongod

now run mongo shell use following commands

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

Re-start the MongoDB instance with access control.

mongod --auth

Now authenticate yourself from the command line using

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

I read it from

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

WAF
  • 1,003
  • 3
  • 15
  • 31
PRAVESH kumar
  • 121
  • 1
  • 2
  • 1
    i defined a user, with root, then add more and more till i find you, `MongoDB Enterprise > db.system.users.find() { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SC RAM-SHA-1" : { "iterationCount" : 10000, "salt" : "k96PCEflidMY5seVju+gAw==", "s toredKey" : "CabQTnJtny7cv0wT5X8oX9QOn3A=", "serverKey" : "RJyCdnlIhyIfj2+d44L61 bYK+MU=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" }, { "role" : "dbAdmin", "db" : "admin" }, { "role" : "userAdmin", "db" : "admin" }, { "role" : "root", "db" : "admin" } ] }` still authentication fails – Hassan Faghihi Jun 11 '17 at 15:16
  • i even used db.changeUserPassword(), or any thing it was, even after that, when i call db.auth('admin', 'my pass') or the way you done it, it says authentication failed for user admin – Hassan Faghihi Jun 11 '17 at 15:18
  • Use `root` role to provides access to the operations and all the resources of the following roles combined... [role root](https://docs.mongodb.com/manual/reference/built-in-roles/#root) – Laode Muhammad Al Fatih Feb 17 '20 at 23:31
11

This is what I did on Ubuntu 18.04:

$ sudo apt install mongodb
$ mongo
> show dbs
> use admin
> db.createUser({  user: "root",  pwd: "rootpw",  roles: [ "root" ]  })  // root user can do anything
> use lefa
> db.lefa.save( {name:"test"} )
> db.lefa.find()
> show dbs
> db.createUser({  user: "lefa",  pwd: "lefapw",  roles: [ { role: "dbOwner", db: "lefa" } ]  }) // admin of a db
> exit
$ sudo vim /etc/mongodb.conf
auth = true
$ sudo systemctl restart mongodb
$ mongo -u "root" -p "rootpw" --authenticationDatabase  "admin"
> use admin
> exit
$ mongo -u "lefa" -p "lefapw" --authenticationDatabase  "lefa"
> use lefa
> exit
Jinmin
  • 205
  • 1
  • 3
  • 10
5

User creation with password for a specific database to secure database access :

use dbName

db.createUser(
   {
     user: "dbUser",
     pwd: "dbPassword",
     roles: [ "readWrite", "dbAdmin" ]
   }
)
Hasib Kamal Chowdhury
  • 2,476
  • 26
  • 28
5

Follow the below steps in order

  • Create a user using the CLI
use admin
db.createUser(
  {
    user: "admin",
    pwd: "admin123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
  • Enable authentication, how you do it differs based on your OS, if you are using windows you can simply mongod --auth in case of linux you can edit the /etc/mongod.conf file to add security.authorization : enabled and then restart the mongd service
  • To connect via cli mongo -u "admin" -p "admin123" --authenticationDatabase "admin". That's it

You can check out this post to go into more details and to learn connecting to it using mongoose.

rahil471
  • 304
  • 2
  • 7
5

mongodb 4.4.13 community

1. create database user

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

1.2 verify working

> db.auth('myUserAdmin','abc123')

< { ok: 1 }

if it fails you get

> db.auth('myUserAdmin','amongus')

MongoServerError: Authentication failed.

2. modify /etc/mongod.conf

nano /etc/mongod.conf

change:

#security:

to:

security:
  authorization: enabled

3. restart mongod service

sudo service mongod restart

this is what worked for me.

Kelvin Wang
  • 627
  • 5
  • 21
4

The best practice to connect to mongoDB as follow:

  1. After initial installation,

    use admin

  2. Then run the following script to create admin user

    db.createUser(
     {
         user: "YourUserName",
         pwd: "YourPassword",
         roles: [
                   { role: "userAdminAnyDatabase", db: "admin" },
                   { role: "readWriteAnyDatabase", db: "admin" },
                   { role: "dbAdminAnyDatabase", db: "admin" },
                   { role: "clusterAdmin", db: "admin" }
                ]
     })

the following script will create the admin user for the DB.

  1. log into the db.admin using

    mongo -u YourUserName -p YourPassword admin

  2. After login, you can create N number of the database with same admin credential or different by repeating the 1 to 3.

This allows you to create different user and password for the different collection you creating in the MongoDB

turivishal
  • 34,368
  • 7
  • 36
  • 59
Balaji.J.B
  • 618
  • 7
  • 14
  • after this go to sudo nano /etc/mongod.conf and put this line security.authorization: enabled, you can see the reference link here : https://stackoverflow.com/a/57384027/3904109 – DragonFire May 16 '20 at 23:08
4

This is what i did for ubuntu 20.04 and mongodb enterprise 4.4.2:

  1. start mongo shell by typing mongo in terminal.

  2. use admin database:

use admin
  1. create a new user and assign your intended role:
use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
  1. exit mongo and add the following line to etc/mongod.conf:
security:
    authorization: enabled
  1. restart mongodb server

(optional) 6.If you want your user to have root access you can either specify it when creating your user like:

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

or you can change user role using:

db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])
ma_jafari
  • 1,021
  • 1
  • 6
  • 24
4

Some of the answers are sending mixed signals between using --auth command line flag or setting config file property.

security:
  authorization: enabled

I would like to clarify that aspect. First of all, authentication credentials (ie user/password) in both cases has to be created by executing db.createUser query on the default admin database. Once credentials are obtained, there are two ways to enable authentication:

  1. Without a custom config file: This is when the former auth flag is applicable. Start mongod like: usr/bin/mongod --auth
  2. With a custom config file: This is when the latter configs has to be present in the custom config file.Start mongod like: usr/bin/mongod --config <config file path>

To connect to the mongo shell with authentication: mongo -u <user> -p <password> --authenticationDatabase admin

--authenticationDatabase here is the database name where the user was created. All other mongo commands like mongorestore, mongodump accept the additional options ie -u <user> -p <password> --authenticationDatabase admin

Refer to https://docs.mongodb.com/manual/tutorial/enable-authentication/ for details.

Binita Bharati
  • 5,239
  • 1
  • 43
  • 24
3

These steps worked on me:

  1. write mongod --port 27017 on cmd
  2. then connect to mongo shell : mongo --port 27017
  3. create the user admin : use admin db.createUser( { user: "myUserAdmin", pwd: "abc123", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
  4. disconnect mongo shell
  5. restart the mongodb : mongod --auth --port 27017
  6. start mongo shell : mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
  7. To authenticate after connecting, Connect the mongo shell to the mongod: mongo --port 27017
  8. switch to the authentication database : use admin db.auth("myUserAdmin", "abc123"
Pang
  • 9,564
  • 146
  • 81
  • 122
Kevin Niasta
  • 117
  • 1
  • 5
3

You'll need to switch to the database you want the user on (not the admin db) ...

use mydatabase

See this post for more help ... https://web.archive.org/web/20140316031938/http://learnmongo.com/posts/quick-tip-mongodb-users/

Fusseldieb
  • 1,324
  • 2
  • 19
  • 44
Justin Jenkins
  • 26,590
  • 6
  • 68
  • 1,285
2

after you create new user, please don't forget to grant read/write/root permission to the user. you can try the

cmd: db.grantRolesToUser('yourNewUsername',[{ role: "root", db: "admin" }])

Rajat Mishra
  • 3,635
  • 4
  • 27
  • 41
Haisheng Yu
  • 191
  • 1
  • 4
1

Many duplicate answers but I think they miss an important note:

Even when authentication is enabled properly you can connect to the Mongo database without username/password!

However, you can execute only harmless commands like db.help(), db.getMongo(), db.listCommands(), etc.

$ mongo 
MongoDB shell version v4.4.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f662858b-8658-4e33-a735-120e3639c131") }
MongoDB server version: 4.4.3
mongos> db.getMongo()
connection to 127.0.0.1:27017
mongos> db
test
mongos> db.version()
4.4.3
mongos> db.runCommand({connectionStatus : 1})
{
        "authInfo" : {
                "authenticatedUsers" : [ ],
                "authenticatedUserRoles" : [ ]
        },
        "ok" : 1,
        "operationTime" : Timestamp(1618996970, 2),
        "$clusterTime" : {
                "clusterTime" : Timestamp(1618996970, 2),
                "signature" : {
                        "hash" : BinData(0,"Kre9jvnJvsW+OVCl1QC+eKSBbbY="),
                        "keyId" : NumberLong("6944343118355365892")
                }
        }
}
Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
1

I have done this in version 6.0 how to set user name and password for a database;

install MongoDB 6.0 or higher create database(whatever the name may be) in MongoDB using compass

enter image description here install MongoDB Shell https://www.mongodb.com/try/download/shell

open cmd

cd C:\Program Files\mongosh

mongosh "mongodb://localhost:27017"

use #your database name#

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

enter image description here

Vinod Joshi
  • 7,696
  • 1
  • 50
  • 51