0

In mongo shell, I ran the following commands:

use mydatabase
db.createUser( { user: "john", pwd: "mongopass", roles: [ "readWrite", "dbAdmin" ] });

Mongo reported a success response. So then from terminal, I typed mongo --username john --password, and when prompted for password, I typed mongopass. But the result I got was:

connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: Authentication failed. :
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1

How do I login to mongodb with a username and password?


This is my /etc/mongo.conf

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1


#security:

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options

#auditLog:

#snmp:
3
  • Can you add your mongo.conf file, there is a option for auth enable. Did you enable that? – Yunus UYANIK Oct 26 '20 at 20:40
  • OK i just added my /etc/mongo.conf – John Oct 26 '20 at 20:42
  • Typically users are created in internal database admin rather than mydatabase or any other custom DB. Honestly I don't know any use case where it would make sense to create users in any other database than admin. Maybe if you run a giant MongoDB which hosts a bunch of fully independent applications. – Wernfried Domscheit Oct 27 '20 at 10:04
1

MongoDB auth setting is false as a default.

First of all, you should create the root user.

//create new user with the root role (also, named root):
use admin
db.createUser({
  user: "root",
  pwd: "pass",
  roles : [ "root" ]
})

After that, you should start your mongod service with the auth option, it means authentication is enabled.

mongod --auth

Also, you can add your mongod.conf file this parameter :

security:
    authorization: enabled

And start your mongod with the command which is below.

mongod --config /etc/mongod.conf //your mongod.conf path

Check this out for more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.