Error authentication failed mongodb

I create a user with the following set of commands. This should create user in both admin db as well as my target db (c2d): # mongo 127.0.0.1:27017 MongoDB shell version: 3.2.6-29-g5c19788 connect...

I create a user with the following set of commands. This should create user in both admin db as well as my target db (c2d):

# mongo 127.0.0.1:27017
MongoDB shell version: 3.2.6-29-g5c19788
connecting to: 127.0.0.1:27017/test
> use admin
switched to db admin
> show collections
system.users
system.version
> db.system.users.find()
> db.createUser({user:"cd2", pwd:"cd2", roles:[{role:"dbOwner", db: "c2d"}]})
Successfully added user: {
    "user" : "cd2",
    "roles" : [
        {
            "role" : "dbOwner",
            "db" : "c2d"
        }
    ]
}
> db.system.users.find()
{ "_id" : "admin.cd2", "user" : "cd2", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "4g6t9kC+godz7k6QQOfD+A==", "storedKey" : "m3tDZBQDU2Tlb1lIjLGyTHmr2QQ=", "serverKey" : "GSA4OXSod1s8mBuZBtfmXq2tlTo=" } }, "roles" : [ { "role" : "dbOwner", "db" : "c2d" } ] }
> use c2d
switched to db c2d
> db.createUser({user:"cd2", pwd:"cd2", roles:[{role:"dbOwner", db: "c2d"}]})
Successfully added user: {
    "user" : "cd2",
    "roles" : [
        {
            "role" : "dbOwner",
            "db" : "c2d"
        }
    ]
}
> use admin
switched to db admin
> db.system.users.find()
{ "_id" : "admin.cd2", "user" : "cd2", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "4g6t9kC+godz7k6QQOfD+A==", "storedKey" : "m3tDZBQDU2Tlb1lIjLGyTHmr2QQ=", "serverKey" : "GSA4OXSod1s8mBuZBtfmXq2tlTo=" } }, "roles" : [ { "role" : "dbOwner", "db" : "c2d" } ] }
{ "_id" : "c2d.cd2", "user" : "cd2", "db" : "c2d", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "vnMjnjfykVQS8ujQXeWaYw==", "storedKey" : "OYXivkmIwuTavlwTGfjrspT6j2E=", "serverKey" : "lw8xqzAaW8V4IQ9wOmQrG2VSp88=" } }, "roles" : [ { "role" : "dbOwner", "db" : "c2d" } ] }

If I try to login, I’m welcomed with an error message:

# mongo 127.0.0.1:27017/c2d -u c2d -p c2d
MongoDB shell version: 3.2.6-29-g5c19788
connecting to: 127.0.0.1:27017/c2d
2016-05-22T10:35:41.862+0100 E QUERY    [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow@src/mongo/shell/db.js:1441:20
@(auth):6:1
@(auth):1:2

exception: login failed

Then I enable security features in the conf file and restart the server:

security:
  authorization: enabled

Error is still the same:

# mongo 127.0.0.1:27017/c2d -u c2d -p c2d
MongoDB shell version: 3.2.6-29-g5c19788
connecting to: 127.0.0.1:27017/c2d
2016-05-22T10:37:43.713+0100 E QUERY    [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow@src/mongo/shell/db.js:1441:20
@(auth):6:1
@(auth):1:2

exception: login failed

Today after an update to Linux and a reboot, I became unable to authenticate on my MongoDB server.

If you don’t care about the details you can skip and read the TLDR below.

It went like this:

# mongo
MongoDB shell version v3.6.21
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("facc876b-82e0-409e-bf99-864b1a415609") }
MongoDB server version: 3.6.21
> use my_db
> db.auth([username], [password])
Error: Authentication failed.
0
>

What happened? Did my database get corrupted?…

I opened the MongDB logs (tail -f /var/log/mongodb/mongod.log) and restarted the server (systemctl restart mongod) and got this wall of logs:

2020-12-02T01:07:08.005+0000 I CONTROL  [main] ***** SERVER RESTARTED *****
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten] MongoDB starting : pid=2216 port=27017 dbpath=/var/lib/mongodb 64-bit host=[hostname]
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten] db version v3.6.21
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten] git version: 1cd2db51dce4b16f4bc97a75056269df0dc0bddb
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.2n  7 Dec 2017
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten] allocator: tcmalloc
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten] modules: none
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten] build environment:
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten]     distmod: ubuntu1604
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten]     distarch: x86_64
2020-12-02T01:07:08.024+0000 I CONTROL  [initandlisten]     target_arch: x86_64
2020-12-02T01:07:08.025+0000 I CONTROL  [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1", port: 27017 }, processManagement: { timeZoneInfo: "/usr/share/zoneinfo" }, storage: { dbPath: "/var/lib/mongodb", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
2020-12-02T01:07:08.025+0000 I STORAGE  [initandlisten] exception in initAndListen: DBPathInUse: Unable to lock the lock file: /var/lib/mongodb/mongod.lock (Resource temporarily unavailable). Another mongod instance is already running on the /var/lib/mongodb directory, terminating
2020-12-02T01:07:08.025+0000 F -        [initandlisten] Invariant failure globalStorageEngine src/mongo/db/service_context_d.cpp 272
2020-12-02T01:07:08.025+0000 F -        [initandlisten] nn***aborting after invariant() failurenn
2020-12-02T01:07:08.037+0000 F -        [initandlisten] Got signal: 6 (Aborted).

 0x55dd778a8d11 0x55dd778a7f29 0x55dd778a840d 0x7f4829331980 0x7f4828f6cfb7 0x7f4828f6e921 0x55dd75f54dc0 0x55dd76205288 0x55dd77747d61 0x55dd77743e47 0x55dd75fce851 0x55dd778a0885 0x55dd75f563d4 0x55dd75eef07c 0x55dd75fd5753 0x55dd75f57339 0x7f4828f4fbf7 0x55dd75fbd9b9
----- BEGIN BACKTRACE -----
{"backtrace":[{"b":"55DD755B6000","o":"22F2D11","s":"_ZN5mongo15printStackTraceERSo"},{"b":"55DD755B6000","o":"22F1F29"},{"b":"55DD755B6000","o":"22F240D"},{"b":"7F482931F000","o":"12980"},{"b":"7F4828F2E000","o":"3EFB7","s":"gsignal"},{"b":"7F4828F2E000","o":"40921","s":"abort"},{"b":"55DD755B6000","o":"99EDC0","s":"_ZN5mongo12verifyFailedEPKcS1_j"},{"b":"55DD755B6000","o":"C4F288","s":"_ZN5mongo20ServiceContextMongoD9_newOpCtxEPNS_6ClientEj"},{"b":"55DD755B6000","o":"2191D61","s":"_ZN5mongo14ServiceContext20makeOperationContextEPNS_6ClientE"},{"b":"55DD755B6000","o":"218DE47","s":"_ZN5mongo6Client20makeOperationContextEv"},{"b":"55DD755B6000","o":"A18851"},{"b":"55DD755B6000","o":"22EA885"},{"b":"55DD755B6000","o":"9A03D4","s":"_ZN5mongo8shutdownENS_8ExitCodeERKNS_16ShutdownTaskArgsE"},{"b":"55DD755B6000","o":"93907C","s":"_ZZN5mongo13duration_castINS_8DurationISt5ratioILl1ELl1000EEEES2_ILl1ELl1EEEET_RKNS1_IT0_EEENKUlvE_clEv"},{"b":"55DD755B6000","o":"A1F753","s":"_ZN5mongo11mongoDbMainEiPPcS1_"},{"b":"55DD755B6000","o":"9A1339","s":"main"},{"b":"7F4828F2E000","o":"21BF7","s":"__libc_start_main"},{"b":"55DD755B6000","o":"A079B9","s":"_start"}],"processInfo":{ "mongodbVersion" : "3.6.21", "gitVersion" : "1cd2db51dce4b16f4bc97a75056269df0dc0bddb", "compiledModules" : [], "uname" : { "sysname" : "Linux", "release" : "4.15.0-124-generic", "version" : "#127-Ubuntu SMP Fri Nov 6 10:54:43 UTC 2020", "machine" : "x86_64" }, "somap" : [ { "b" : "55DD755B6000", "elfType" : 3, "buildId" : "A43721619F38ECCCF865593B38977EBB8CA06224" }, { "b" : "7FFC961AE000", "path" : "linux-vdso.so.1", "elfType" : 3, "buildId" : "2F65AB6DA6CED1362D99E2FD4939F338194673AC" }, { "b" : "7F482A5AC000", "path" : "/lib/x86_64-linux-gnu/libresolv.so.2", "elfType" : 3, "buildId" : "3D39CDDB9265E8DD55E354DA80F9CD219DB3FB28" }, { "b" : "7F482A168000", "path" : "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.0", "elfType" : 3, "buildId" : "4778D155198D2C078070C118F6C2A15E75D7C75F" }, { "b" : "7F4829F00000", "path" : "/usr/lib/x86_64-linux-gnu/libssl.so.1.0.0", "elfType" : 3, "buildId" : "4167AEDD060DA4C48A3221FDEEFBE42FEA3D1CC2" }, { "b" : "7F4829CFC000", "path" : "/lib/x86_64-linux-gnu/libdl.so.2", "elfType" : 3, "buildId" : "2568A7F2BACBB283FA3F5ED6B68133409C9DAD31" }, { "b" : "7F4829AF4000", "path" : "/lib/x86_64-linux-gnu/librt.so.1", "elfType" : 3, "buildId" : "51D903A839765BFA7A3AE4B5E6A73EA8E71BC129" }, { "b" : "7F4829756000", "path" : "/lib/x86_64-linux-gnu/libm.so.6", "elfType" : 3, "buildId" : "5F1BA80882969AE923E63130BE993DE80B4551ED" }, { "b" : "7F482953E000", "path" : "/lib/x86_64-linux-gnu/libgcc_s.so.1", "elfType" : 3, "buildId" : "679F3AE11120EC7C483BC9295345D836F5C104F7" }, { "b" : "7F482931F000", "path" : "/lib/x86_64-linux-gnu/libpthread.so.0", "elfType" : 3, "buildId" : "AE13B309B7DE1CC2B1CBC7605FC174DAC01A90FC" }, { "b" : "7F4828F2E000", "path" : "/lib/x86_64-linux-gnu/libc.so.6", "elfType" : 3, "buildId" : "CC6DD208D3AF4BC505F599A90EF8AF52F16116E4" }, { "b" : "7F482A7C6000", "path" : "/lib64/ld-linux-x86-64.so.2", "elfType" : 3, "buildId" : "0A5772E6599F66B61B7851DB8EB10D257F4C1993" } ] }}
 mongod(_ZN5mongo15printStackTraceERSo+0x41) [0x55dd778a8d11]
 mongod(+0x22F1F29) [0x55dd778a7f29]
 mongod(+0x22F240D) [0x55dd778a840d]
 libpthread.so.0(+0x12980) [0x7f4829331980]
 libc.so.6(gsignal+0xC7) [0x7f4828f6cfb7]
 libc.so.6(abort+0x141) [0x7f4828f6e921]
 mongod(_ZN5mongo12verifyFailedEPKcS1_j+0x0) [0x55dd75f54dc0]
 mongod(_ZN5mongo20ServiceContextMongoD9_newOpCtxEPNS_6ClientEj+0x158) [0x55dd76205288]
 mongod(_ZN5mongo14ServiceContext20makeOperationContextEPNS_6ClientE+0x41) [0x55dd77747d61]
 mongod(_ZN5mongo6Client20makeOperationContextEv+0x27) [0x55dd77743e47]
 mongod(+0xA18851) [0x55dd75fce851]
 mongod(+0x22EA885) [0x55dd778a0885]
 mongod(_ZN5mongo8shutdownENS_8ExitCodeERKNS_16ShutdownTaskArgsE+0x381) [0x55dd75f563d4]
 mongod(_ZZN5mongo13duration_castINS_8DurationISt5ratioILl1ELl1000EEEES2_ILl1ELl1EEEET_RKNS1_IT0_EEENKUlvE_clEv+0x0) [0x55dd75eef07c]
 mongod(_ZN5mongo11mongoDbMainEiPPcS1_+0x273) [0x55dd75fd5753]
 mongod(main+0x9) [0x55dd75f57339]
 libc.so.6(__libc_start_main+0xE7) [0x7f4828f4fbf7]
 mongod(_start+0x29) [0x55dd75fbd9b9]
-----  END BACKTRACE  -----

Welcome to the world of Linux. What usually works unexpectedly doesn’t anymore. And to troubleshoot it, you have to find the needle in the haystack. The important information in here is:

DBPathInUse: Unable to lock the lock file: /var/lib/mongodb/mongod.lock (Resource temporarily unavailable). Another mongod instance is already running on the /var/lib/mongodb directory, terminating

After deleting this file (rm /var/lib/mongodb/mongod.lock) and starting again, I get another wall of text, and this time the important information is this:

Failed to set up listener: SocketException: Address already in use

So I check open ports and get this list:

# netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      1151/mongod         
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      622/systemd-resolve 
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1103/sshd           
tcp6       0      0 :::80                   :::*                    LISTEN      1180/apache2        
tcp6       0      0 :::22                   :::*                    LISTEN      1103/sshd           
tcp6       0      0 :::3000                 :::*                    LISTEN      1422/node           
tcp6       0      0 :::443                  :::*                    LISTEN      1180/apache2        
udp        0      0 127.0.0.53:53           0.0.0.0:*                           622/systemd-resolve

Not sure what happened to that very first instance who managed to run but not initialize correctly. I kill it (kill 1151) and try restarting MongoDB again. This time the error is:

Failed to unlink socket file /tmp/mongodb-27017.sock Operation not permitted

So I delete this file too (rm /tmp/mongodb-27017.sock) and try yet again. This time it runs and tells me:

** WARNING: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted.

Waaaaaait. Does it mean that upon restart, the MongoDB daemon started with authentication disabled, and so, any attempt to authenticate would fail?

According to the official MongoDB tutorial on authentication, this option is disabled by default. So I open the config vim /etc/mongod.conf and add the setting as instructed:

security:
    authorization: enabled

I restart a final time and this time, it initializes without any warning. I try to authenticate and it works. Phew!

So I try to authenticate once again and… Same error! Authentication failed. What??? So I check the command history to get a grasp of what I did back then. It looks like I had changed the db path to /data/db but didn’t change the conf file. Wow. So I update /etc/mongod.conf and run again. This time it works and I can finally authenticate.

TLDR

So what happened was:

  • I manually ran MongoDB with authentication enabled with a non-default path to the database.
  • Upon restart the server used an empty database.
  • Any attempt to authenticate failed.
  • Changed the MongoDB config to enable authentication and to use the non-default path.
  • Restarted the server with authentication enabled.

Securing data is always a primary concern in database management.

Usually, MongoDB error auth failed, occurs when using an improper authentication method.

To restrict MongoDB we need to add an admin user and then enable access control.

At Bobcares, we often get requests to fix MongoDB errors, as a part of our Server Management Services.

Today, let’s discuss how our Support Engineers enable access control in MongoDB.

Auth failed error in MongoDB

Authentication is important for preventing unauthorized access. By enabling auth, MongoDB verifies the users to determine their access.

Users will have well-defined roles and it’s important to verify it before using the database. This is to ensure security over the data stored.

Usually, MongoDB shows auth failed errors when it uses an improper auth method.

When a user tries to access the database using the auth user, it shows up the error as,

MongoDB error Auth failed for user.

Here, MongoDB could not identify the user. This indicates that the auth method was not proper. As a result, the login attempt ends up in a failed status.

Method to enable Authentication in MongoDB

Authentication adds security over any system. But, enabling access control in MongoDB databases often shows errors.

Usually, this is because of improper auth methods. Our Dedicated Engineers with expertise over a decade enables auth in databases. Now, let’s discuss how we authenticate a user in the MongoDB server.

Step 1: Create an admin user

Initially, to enable access control our Support Engineers create an admin user. In the mongod shell, we add a user with admin privilege in the admin database.

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

Further, we restart the mongod shell as an admin user. Firstly, we shut down the currently using shell. And, to start again we use the command,

mongod --auth --port 27017 --dbpath <dbpath>

Usually, there are two ways to enable access control. That is, either during connection or after connecting.

a. Authenticate during connection

To authenticate a user during connecting we use the command,

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

Now, we enter the password when prompted. This successfully enables access control to the admin user.

Hence, the admin user can now add as many users as needed.

b. Authenticate after connecting

On the other hand, we can authenticate the user after connecting. To connect to mongo shell, we use the command,

mongo --port 27017

Now we have entered the shell. Next, we switch to admin using the command,

use admin
db.auth("myUserAdmin", passwordPrompt())

Here, we enter the password. Hence, now the admin user has permission to create a new user.

Step 2: Creating users and authenticating

So far, we have created an admin user. This admin user can now create new users. Afterward, the admin user can authenticate new users.

Firstly, our Support Engineers create a new user as we created the admin user.

We give access control to the user as required. Now, we have a newly created auth user. In addition, to ensure the auth we enter the mongo shell using the created user.

Finally, our MongoDB Experts check the config file to see the security authorization parameter. The mongod.conf appear as

MongoDB error auth failed, config file.

Application-specific auth

By default, MongoDB users are scoped to particular databases. Therefore, even if the users have cross-DB privileges, authentication may not work. That is if the user isn’t defined on DB auth will simply fail.

That’s why, in applications like Mongoose, we enable auth using the format:

mongoose.connect('mongodb://user:password@host/yourDB?authSource=yourDB&w=1')

[Still having difficulty in fixing MongoDB errors? – We’ll fix it.]

Conclusion

In short, MongoDB error Auth failed occurs due to improper enabling of access control. Today, we saw how our Support Engineers enable authentication for MongoDB users.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

I have made connection to cloud.mongodb.com with node.js but I don’t understand why and how I made 2 successful connections but other times connections were unsuccessfull .
image

In Console I see

the server/replset/mongos options are deprecated, all their options are supported at the top level of the options object [poolSize,ssl,sslValidate,sslCA,sslCert,sslKey,sslPass,sslCRL,autoReconnect,noDelay,keepAlive,connectTimeoutMS,fa
mily,socketTimeoutMS,reconnectTries,reconnectInterval,ha,haInterval,replicaSet,secondaryAcceptableLatencyMS,acceptableLatencyMS,connectWithNoPrimary,authSource,w,wtimeout,j,forceServerObjectId,serializeFunctions,ignoreUndefined,raw,bu
fferMaxEntries,readPreference,pkFactory,promiseLibrary,readConcern,maxStalenessSeconds,loggerLevel,logger,promoteValues,promoteBuffers,promoteLongs,domainsEnabled,keepAliveInitialDelay,checkServerIdentity,validateOptions,appname,auth]

(node:3268) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: authentication fail
(node:3268) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Cover image for How to fix the error 'MongoServerError: bad auth : Authentication failed'?

Shafia Rahman Chowdhury

Oftentimes, you might come across the error «bad auth: authentication failed.» What does this error mean? «Bad auth» means the authentication method is not proper due to providing wrong username or password; hence, it failed.

This blog will discuss the possible mistakes we make for which this error appears and the solutions we can try to fix the error.

1) Using whitespaces

When you put your username and password, do not add any whitespace (extra space) before and after your username and password in the MongoDB string connection.

Wrong

Image description

Image description

Correct

Image description

Image description

2) username and password did not match

Check if the username and password in your MongoDB connection string matches with the username and password in your database access

Correct: Username and password matches

MongoDB connection string
Image description

Database Access
Image description

3) Forgot to save username and password

Make sure you have clicked the ‘Add User’ button after creating the username and password in your database access.

Image description

Image description

4) Using angle brackets

Do not put your username and password inside the angle brackets like the picture below:

Wrong

Image description

Correct

Image description

5) Environment variables did not match

If you are using environment variables, make sure you have written them correctly in your MongoDB connection string

Did not match

Image description

Image description

Matched

Image description

Image description

Take time and go through your code to see if you have made the mistakes discussed above when your authentication fails. I am sure one of these solutions will help you connect your MongoDB successfully. Happy coding!!!

Hey 😍

Want to help the DEV Community feel more like a community?

Head over to the Welcome Thread and greet some new community members!

It only takes a minute of your time, and goes a long way!

Getting data is for the most part a central fear in the informational index parties. MongoDB screw-up auth failed, happens while using an improper confirmation procedure. To bind MongoDB, we need to add a manager customer and thereafter enable access control.

Around here at ARZHOST, we routinely get requests to fix MongoDB errors, as a piece of our Server Management Services.

Today at arzhost.com, “Uncaught Mongo DB Error – Authentication Failed” could we analyze how our Hosting Expert Planners engage access control in MongoDB.

Auth attacked error in MongoDB

Confirmation is huge for hindering unapproved access. By enabling auth, MongoDB looks at the customers to choose their entry. Customers will play obvious parts and it’s essential to look at it before using the informational collection. This is to ensure security over the data set aside.

Generally, MongoDB shows auth attacked errors when it uses an improper auth method. Exactly when a customer actions to get to the database using the auth customer, it seems the slip-up as,

Here at arzhost.com, MongoDB couldn’t perceive the customer. This shows that the auth strategy was not proper. Consequently, “Uncaught Mongo DB Error – Authentication Failed” the login attempt ends up in an attacked status.

Procedure to engage Authentication in MongoDB

The statement adds security over any structure. In any case, enabling access control in MongoDB informational collections routinely shows errors.

Ordinarily, this is a consequence of unseemly auth methods. Our Hosting Expert Planners with governance over 10 years enable auth in informational indexes. “Uncaught Mongo DB Error – Authentication Failed” By and by, could we inspect how we approve a customer in the MongoDB server.

Stage 1: Create a director customer

From the beginning, to engage access control our Hosting Expert Planners make a management customer. In the MongoDB shell, we add a customer with overseer honor in the head database.

  • use chairman
  • create User (
  • {
  • customer: "myUserAdmin",
  • pwd: password Prompt (),
  • occupations: [ {work: "userAdminAnyDatabase", db: "chairman”}, "readWriteAnyDatabase”]
  • }
  • )

Extra, we restart the MongoDB shell as an executive customer. First thing, we shut down the by and by using the shell. Additionally, to start again we use the request:

  • MongoDB - - auth-port 27017 - - dB path <dB path>

For the most part, there are two techniques for enabling access control. “Uncaught Mongo DB Error – Authentication Failed” That is, either during affiliation or following interacting.

A: Confirm during affiliation

To confirm a customer during shared we use the request,

  • mongo - - port 27017 - - authentication Database "director" - u "my user admin" - p

By and by, we enter the mystery key when prompted. This viably enables access control to the head customer.

Consequently, the manager customer can now add anyway numerous customers relying upon the circumstance.

B: Confirm right after interacting

On the other hand, we can check the customer following interaction. To communicate with mongo shell, we use the request:

  • mongo - - port 27017

By and by we have entered the shell. Then, at that point, we change to the manager using the request:

  • use chairman
  • Auth (“my user admin”, password Prompt ())

Here at arzhost.com, “Uncaught Mongo DB Error – Authentication Failed” we enter the mystery word. Later, by and by the chairman customer has the approval to make another customer.

Stage 2: Creating customers and confirming

Up until this point, we have made an overseer customer. This director customer can now make new customers. A brief time frame later, the head customer can confirm new customers.

First thing, our Hosting Expert Planners make one more customer as we made the manager customer.

We give access control to the customer as required. By and by, we have an as of late made auth customer. “Uncaught Mongo DB Error – Authentication Failed” Besides, to ensure the auth we enter the mongo shell using the made customer.

Finally, our MongoDB Experts check the config report to see the security confirmation limit. The MongoDB. conf appears as.

Application-express auth

Normally, MongoDB customers are checked to explicit informational indexes. As such, whether or not the customers have cross-DB approvals. “Uncaught Mongo DB Error – Authentication Failed” confirmation may not work. That is in case the customer isn’t described on DB auth will miss the mark.

That is the explanation, in applications like Mongoose, we engage auth using the arrangement:

  • connect('mongodb://user:password@host/yourDB?authSource=yourDB&w=1')

Mongo Error: Authentication failed

It might be disappointing to begin a dissecting action, and get a message like Mongo Error: Authentication failed. Particularly, if you hate MongoDB Compass.

A couple of ordinary issues might be with entries on the Auth tab: are the username and mystery word spelled precisely, with the legitimate upper and lower cases, and is the Auth source right (a significant part of the time it should be left unfilled or use the default “manager”.)

However, there could be various hints. “Uncaught Mongo DB Error – Authentication Failed” Compass and ARZHOST use comparable programming libraries to connect with MongoDB events, whether or not on-premises or Atlas.

Just to guarantee that the connection string is vague from what you have in Compass, is to copy/stick from Compass into ARZHOST. Here are the means:

  • Open Compass, select the affiliation, and snap on the Edit button:
  • Click Confirm
  • in the change window, press ctrl+A to pick the entire string, then, ctrl+C to copy the string to the clipboard:
  • In ARZHOST MongoDB model affiliations settings, add another, and press the button “From SRV or URI”:
  • then, press ctrl+V or right-snap and pick stick:

Right when you save, this should parse the string and fill in all of the entries thus. Then, effort again to connect with the database. “Uncaught Mongo DB Error – Authentication Failed” using the as of late made connection settings.

Termination

Thus, MongoDB error Auth failed occurs due to improper enabling of access control. Today at arzhost.com, “Uncaught Mongo DB Error – Authentication Failed” we saw how our Hosting Expert Planners enable approval for MongoDB customers.

Read More

MongoDb Shutting Down with Code 100

As per your log statement it seems like that you are committing mistake in your authentication statement such as in your statement

mongo 127.0.0.1:27017 --authenticationDatabase admin -u admin -p

As per MongoDB BOL documentation here With access control enabled, ensure you have a user with userAdmin or userAdminAnyDatabase role in the admin database. This user can administrate user and roles such as: create users, grant or revoke roles from users, and create or modify customs roles.

Connect and authenticate as the user administrator

Using the mongo shell, you can:

  • Connect with authentication by passing in user credentials, or

  • Connect first withouth authentication, and then issue the db.auth()
    method to authenticate.

For example, the following creates the user myUserAdmin in the admin database:

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

To authenticate during connection

Start a mongo shell with the -u , -p , and the —authenticationDatabase command line options:

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

To authenticate after connecting

Connect the mongo shell to the mongod:

mongo --port 27017

Switch to the authentication database (in this case, admin), and use db.auth(<username>, <pwd>) method to authenticate:

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

As I am able to see that in your below mention mongod.conf file the authorization : enable . It’s means your authentication is enable. So, there is no issue in your mongod.conf file.

systemLog:
  destination: file
  path: /Users/me/Web/blog/setup/logs/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /usr/local/var/mongodb
net:
  port: 27017
  bindIp: 127.0.0.1
security:
  authorization: enabled

For your further ref here and here

Понравилась статья? Поделить с друзьями:
  • Error auth master userdb list user listing returned failure
  • Error audit support not in kernel
  • Error audit no package json found cannot audit a project without a package json
  • Error audio device is set to a sample rate not supported by soundwire
  • Error attribute redirect not allowed on element form at this point