Mongo server error bad auth authentication failed

I'm trying to connect to my mongoDB server via the connection string given to me by mongo: "mongodb+srv://david:password@cluster0-re3gq.mongodb.net/test?retryWrites=true" In my code I am

I’m trying to connect to my mongoDB server via the connection string given to me by mongo:

"mongodb+srv://david:password@cluster0-re3gq.mongodb.net/test?retryWrites=true"

In my code I am calling the connection through mongoose like this (obviously putting in my password):

const mongoose = require('mongoose');
const db = 'mongodb+srv://david:<password>@cluster0-re3gq.mongodb.net/test?retryWrites=true'
mongoose
    .connect(db, { 
        useNewUrlParser: true,
        useCreateIndex: true
      })
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.log(err));

When I run the code I am getting the following error

«MongoError: bad auth Authentication failed.»

Any ideas of what that could mean?

desertnaut's user avatar

desertnaut

56.1k21 gold badges134 silver badges163 bronze badges

asked Apr 15, 2019 at 18:49

Djaenike's user avatar

1

I had the same problem, and in my case, the answer was as simple as removing the angle brackets «<«and «>» around <password>. I had been trying: my_login_id:<my_password>, when it should have been my_login_id:my_password.

answered Apr 17, 2019 at 16:39

Crowdpleasr's user avatar

CrowdpleasrCrowdpleasr

3,3084 gold badges20 silver badges35 bronze badges

1

I think you’re confused with the mongodb account password and user password.
You should use user password, not account password.
That was the reason of my case.

answered Apr 18, 2019 at 18:19

vhurryharry's user avatar

vhurryharryvhurryharry

1,6251 gold badge10 silver badges26 bronze badges

6

It happens because your provided password in connection string is wrong and most probably you have mistaken cluster password with your login password, in simple words while connecting with Atlas Cluster we can’t use our account password by which we login to the Atlas website. In both case we can reset our cluster password and solve this issue.

To Solve The Issue Follow Below Given Steps

Step 1:- Click Database Access From left Side Navigation of MongoDB Atlas page.

Step 2:- Select your username and and click on the edit button from right side.

Step 3:- Click to change password.

Step 4:- Click update user.

While changing password try to keep password only alphabetical because special characters need encoding.
See The Image For Your Better Understanding

that’s all now you can connect.

answered Oct 22, 2019 at 6:21

Pawan Bishnoi's user avatar

4

Don’t use creds in the URI, use like this instead:

mongoose.connect(mongodb+srv://clusterAnything.mongodb.net/test?retryWrites=true&w=majority, { user: process.env.MONGO_USER, pass: process.env.MONGO_PASSWORD, useNewUrlParser: true, useUnifiedTopology: true })

Nimantha's user avatar

Nimantha

6,6806 gold badges27 silver badges66 bronze badges

answered Jan 22, 2020 at 2:24

skipper_dev's user avatar

3

In my case left and right characters are there

like this:

<Password>

so changed to:

Password

Nimantha's user avatar

Nimantha

6,6806 gold badges27 silver badges66 bronze badges

answered Jul 5, 2021 at 5:38

Gv Ravi's user avatar

Gv RaviGv Ravi

3032 silver badges3 bronze badges

2

Checklist to follow:

1) Make sure you’re using the correct password (the DB user password and not the Mongo account).

2) When entering your password, make sure all special characters are URL encoded (for example: p@ssword should be p%40ssword).

3) If you don’t remember your password of your DB user — go to Database Access (if you’re using Mongo Atlas) -> select your DB user -> edit -> create a new password -> don’t forget update to click on ‘Update User’.

(!) Security warning: Do not write the password in plain text inside your code — Follow the suggestions given here.

answered Apr 11, 2020 at 15:12

RtmY's user avatar

RtmYRtmY

15.9k10 gold badges105 silver badges111 bronze badges

Are you writing your password in the place of <password>? If your aren’t, a good practice is to create a environment variable on your operating system and call it using process.env.[your variable]. Ex:

const password = process.env.YOURPASSWORDVARIABLE
const db = 'mongodb+srv://david:'+password+'@cluster0-re3gq.mongodb.net/test?retryWrites=true'

Better yet, you can also put your whole url connection string inside a env variable:

answered Apr 15, 2019 at 19:02

ardmont's user avatar

3

Adding to above answers, the issue seemed to revolve around a wrong Database password input for me, because of a distortion of what i read as my current password from the Atlas menu and what MongoDB Atlas really saved as my current password.

There seems to be a «bug» when using the «Copy» button when choosing a new password.

What helped me was the following:

  • Open Atlas in the web
  • Go to «Database Access»
  • Click «Edit» on the Database user
  • Choose «Password» for authentication method
  • Click «Edit Password»
  • Click «Show» in the password field
  • Click «Autogenerate Secure Password»
  • DO NOT press «Copy» button to copy, but use manual selection via mouse and copy the text via right-click of your mouse or keyboard command
  • Click «Update User» below

Then:
Go through the list of Database users to make sure that no other Database user has the same password you just newly generated.

Now try your Username/Password combination again using this connection string (leaving out the placeholder characters ‘$’ and ‘[]’:

‘mongodb+srv://$[username]:$[password]@$[hostlist]/$[database]?retryWrites=true’


I noticed that when I autogenerated a new password by clicking and then clicking the «Copy» button, that the autogenerated password was reset to the old password. Therefore I assumed the new autogenerated password is correct, but in reality it was my old password, which in addition was the same as for another Database user. I could not comprehend that until I clicked «Show» on the password input field.

Nimantha's user avatar

Nimantha

6,6806 gold badges27 silver badges66 bronze badges

answered May 16, 2021 at 9:48

phpaul89's user avatar

Not only the password

Check all the fields it could be the password the user or the database. If you misspelt any of these you will have an authentication error.
Go to the database access on the left pane under security:
enter image description here

And in case change the password using edit button. Let’s say your password is: P@sW0rd
You can compile the URL using the information contained in the Database Users screen:

client = MongoClient("mongodb+srv://giac:P@sW0rd@cluster0.wjdtk.mongodb.net/testc?retryWrites=true&w=majority")

The other answers did not say that even if you mispell the database name you have a authentication error.

answered Jan 23, 2021 at 16:57

G M's user avatar

G MG M

19.8k10 gold badges80 silver badges82 bronze badges

2

This worked for me

    mongoose.connect(
    `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@cluster0.adv0t.mongodb.net/${process.env.MONGO_DATABASE}?retryWrites=true&w=majority`,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }
  );

Create a «.env» file (you need to install dotenv before this ) in the parent directory(if you choose a custom location, add the following in server.js / app.js).

require('dotenv').config({ path: '/custom/path/to/.env' }) //uses custom location

Otherwise, add this in the server.js / app.js (the one that initiates server).

require('dotenv').config() //uses default location

In the «.env» file, define the user, password and database like this

MONGO_USER=uSerName
MONGO_PASS=p@sSW0rd
MONGO_DATABASE=myDatabase

answered Oct 12, 2021 at 13:06

rhythmo's user avatar

rhythmorhythmo

8091 gold badge8 silver badges20 bronze badges

I faced a similar issue, weirdly enough it got resolved when I created a new user in database access. This time though I clicked on autogenerate password. It should not matter but in my case it solved the issue.

answered Nov 17, 2020 at 13:21

Vimath's user avatar

1

I forgot to update the user after generating and copying the password and was wondering why it wasn’t working. I saw the update button later. I was not visible to me earlier. lol. Solved the problem.

Database Access => edit user => generate/copy password => update it!
It worked for me.

remember to make sure you have updated it.

answered Dec 3, 2020 at 21:07

dpthegrey's user avatar

Just remove the angle brackets from both sides of your password.

Wrong Answer :
const db = 'mongodb+srv://username:<password>@cluster0-re3gq.mongodb.net/test?retryWrites=true'

Correct Answer :
const db = 'mongodb+srv://username:password@cluster0-re3gq.mongodb.net/test?retryWrites=true'

Farid Vatani's user avatar

answered Nov 15, 2020 at 14:24

BiplabRoy's user avatar

Finally, it worked for me to used that connection string with a lower grade that NodeJs versions(2.2.12 or later) cluster url. And After that make sure you have to whitelist your current IP Address from Atlas MongoDB. It should display like 0.0.0.0/0 (includes your current IP address) in Network Access section in Atlas MongoDB.
Connect to cluster NodeJs version 2.2.12 or later

And the main issue was where I am storing that connection string url in a constant that part. So initially,I was storing that connection string value in single/double quote but every time I was getting Authentication failure error as it was unable to parse that «Password» value from Atlas mongoDB . So I used backtick («)instead of single/double quote to store that connection string.

Sample code where I am connecting mongoDB Atlas through a NodeJs application.

const DB_USER = 'your username in atlas mongodb';

const PASSWORD = encodeURIComponent('your password in atlas mongodb');

const url = `mongodb://${DB_USER}:${PASSWORD}@cluster0-shard-00-00.3ytbz.mongodb.net:27017,cluster0-shard-00-01.3ytbz.mongodb.net:27017,cluster0-shard-00-02.3ytbz.mongodb.net:27017/sample-db?ssl=true&replicaSet=atlas-z26ao5-shard-0&authSource=admin&retryWrites=true&w=majority`;

mongoose.connect(url,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: true
  })
  .then(() => {
    console.log('Connected to database !!');
  })
  .catch((err)=>{
    console.log('Connection failed !!'+ err.message);
  });

answered Aug 12, 2020 at 14:59

Sagar Chowdhury's user avatar

1

I just had this problem knowing that I was using the correct username, password and DBname.

I tried to change the password for the db user to double check, but it still didn’t work.

I then instead created a new user, gave the user admin role, set the password etc, and then used that new user and password (same dbname) for the connection and it worked.

I don’t know exactly what the issue was, but hoping it can help some of you save some time :)

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Feb 7, 2021 at 21:06

IndustryDesigns's user avatar

IndustryDesignsIndustryDesigns

1,7082 gold badges10 silver badges22 bronze badges

After spending almost an hour messing with the URI, changing permissions and configurations and whatnot, I found out I was getting this error message because of a VPN connection I had active. After shutting down the VPN I was able to connect.

So if nothing else works for you, there might be something in your system preventing a connection to be successfully established and mongodb is just responding with bad auth

answered Oct 22, 2021 at 18:30

Pedro Martins Timóteo da Costa's user avatar

I had this same challenge but I discovered that making my IP address set to my current IP prevented me from accessing the services. Making the database accessible from anywhere was appropriate to access the database either using mongo shell or mongo compass.

answered Apr 13, 2022 at 8:09

Torch's user avatar

TorchTorch

518 bronze badges

The same problem i faced with mongoDB password authentication failed.

«Error: bad auth Authentication failed.»

As per Pawan’s suggestion given above i replaced my login password in MONGO_URI link with database password and it works. be sure to check that one also.

If you not generated the generate new one or if created earlier then replace with new one.

answered Mar 18, 2020 at 7:47

akshay_sushir's user avatar

In my case, my password was wrong, to diagnostic the error, I have been follow the next steps:

I have to try connection by command line:
enter image description here

Whit this command: mongo «mongodb+srv://cluster0-j8ods.mongodb.net/test» —username :

enter image description here

The response was again: 2020-04-26T11:48:27.641-0500 E QUERY [js] Error: bad auth Authentication failed. :

then I’m change the password for my user, in my case, root user. and thats it, I’m authorized

answered Apr 26, 2020 at 16:53

EdwinCab's user avatar

EdwinCabEdwinCab

3103 silver badges15 bronze badges

1

mongodb+srv://jehat123:<password>@jehatarmancdeniz-x2yf7.mongodb.net/question-answer?retryWrites=true&w=majority

Delete all of password part

Use like this:

mongodb+srv://jehat123:yourpass@jehatarmancdeniz-x2yf7.mongodb.net/question-answer?retryWrites=true&w=majority

answered May 2, 2020 at 7:52

armancj2's user avatar

armancj2armancj2

1082 silver badges4 bronze badges

You can also get rid of this error by creating a new database user by going to Database Access from the left side and then go to Add New Database User from right right.
Now create a new username and password, click OK. Now replace this new username and password into the MongoUri.

answered Dec 3, 2020 at 16:10

spetsnaz's user avatar

spetsnazspetsnaz

1411 silver badge5 bronze badges

In My case the above error got resolved by setting password variable directly.

DATABASE = "test"
#PASSWORD = os.environ.get("YOUR_PASSWORD") #This line was causing an error in code
PASSWORD = "YOUR_PASSWORD"                  # I added directly password variable

client = connect(
    DATABASE,
    host=f"mongodb+srv://mano:{PASSWORD}@cluster0.e2arj.mongodb.net/?retryWrites=true&w=majority",
    alias="default",
)

answered Apr 12, 2021 at 4:07

Tejas Ratunawar's user avatar

Changing password worked for me

nB: Not the atlas password

answered Jun 9, 2021 at 10:00

Dojo's user avatar

DojoDojo

5905 silver badges13 bronze badges

mongodb+srv://david:password@cluster0-re3gq.mongodb.net/test?retryWrites=true

  • Replace ‘password’ with the password you registered for the username specified.
  • Replace ‘test’ after net with the name of the db you created in collections.

bguiz's user avatar

bguiz

26k46 gold badges153 silver badges239 bronze badges

answered Jun 23, 2021 at 3:25

Brendan Gaturu's user avatar

For me it turned out to be, that I had to tab out of the password field on the MongoDB Atlas page. Before clicking «Update User»

answered Jul 24, 2021 at 17:47

Paul Smith's user avatar

Paul SmithPaul Smith

1733 silver badges12 bronze badges

enter image description here

Just go to the «MongoDB Users tab» where you will find the user list. Click on edit where you can reset the password. Sometimes resetting the password can resolve the issue.

answered Dec 27, 2021 at 16:42

chinmay prajapat's user avatar

if you having this issue and learning mongo by official mongo trainings use m001-mongodb-basics as password for your db. And the correct db name is Sandbox (if you followed all steps)

answered Jan 3, 2022 at 17:48

kyxap's user avatar

kyxapkyxap

5216 silver badges19 bronze badges

This happened to me recently, I found out if you have updated your Mongo Db Password recently, your older databases will still be using the old password.

You can get around this by adding a new user to your Mongo db account or just use the old password.

answered May 24, 2022 at 15:19

William J Priest's user avatar

1

  1. Go to Database on the left hand side
  2. click on browse collection
  3. click on Add My Own Data
  4. provide database name and collection name
  5. Again click on database
  6. click on connect ,connect your application
  7. Select node.js
  8. copy the connection string and keep it in your server.js
    9)click on database access , edit password, autogenerate password
  9. Copy the password with mouse , click update user
  10. replace in the url string with this password and you are done

answered Jun 28, 2022 at 10:51

Sagar Chawla's user avatar

Содержание

  1. MongoError: Authentication failed #4587
  2. Comments
  3. Footer
  4. MongoDB Error Auth failed – Method to set it up correctly
  5. Auth failed error in MongoDB
  6. Method to enable Authentication in MongoDB
  7. Step 1: Create an admin user
  8. a. Authenticate during connection
  9. b. Authenticate after connecting
  10. Step 2: Creating users and authenticating
  11. Application-specific auth
  12. Conclusion
  13. PREVENT YOUR SERVER FROM CRASHING!

MongoError: Authentication failed #4587

I have mongodb in mongolab.
If I connect to it by command

it is ok.
If I use mongoose and connect by

I use mongoose 4.6.1

The text was updated successfully, but these errors were encountered:

Also, I have checked — bug is not reproduced in 4.4.20 version. It works correctly

Do your username and password include any non alphanumeric characters? Similar issues have surfaced in the past with handling characters like : in passwords

Also, what version of mongoose and mongodb?

Mongodb ‘v3’
No, there is no non-alphanumeric symbols.

Hmm also what database is the user defined on? MongoDB users are scoped to dbs, even if they have cross-db privileges, so if the user you have isn’t defined on db you’ll need to put something like mongoose.connect(‘mongodb://$:$@$/$?authSource=admin’) if the user is defined on the ‘admin’ db.

Also, if you’re on mongodb 3.x, you might be using SCRAM-SHA-1 auth or not. Try both of the below:

  • mongoose.connect(‘mongodb://$:$@$/$?authMechanism=SCRAM-SHA-1′)
  • mongoose.connect(‘mongodb://$:$@$/$?authMechanism=MONGODB-CR’)

@vkarpov15, Yes, it helped! Thank you very much!

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 .

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.

i tryed it , but not work,

mongoose v4.5.3
mongodb v3.4.7

errMsg:
MongoError: Authentication failed. 14|gougouS | at Function.MongoError.create (/www/website/gougouServer/source/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)

just add ?authSource=yourDB&w=1 to end of db url

mongoose.connect(‘mongodb://user:password@host/yourDB?authSource=yourDB&w=1’)
this work for me . &w=1 is important

just add ?authSource=yourDB&w=1 to end of db url

mongoose.connect(‘mongodb://user:password@host/yourDB?authSource=yourDB&w=1’)
this work for me . &w=1 is important

Thank you sir. :3 good answer

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

MongoDB Error Auth failed – Method to set it up correctly

by Keerthi PS | Oct 21, 2019

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,

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.

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,

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,

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,

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

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

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:

[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.

Источник

MongoDB Error Auth failed – Method to set it up correctly

by Keerthi PS | Oct 21, 2019

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,

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.

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,

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,

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,

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

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

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:

[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.

Источник

MongoError: Authentication failed #4587

Comments

yankouskia commented Oct 2, 2016

I have mongodb in mongolab.
If I connect to it by command

it is ok.
If I use mongoose and connect by

I use mongoose 4.6.1

The text was updated successfully, but these errors were encountered:

yankouskia commented Oct 2, 2016 •

Also, I have checked — bug is not reproduced in 4.4.20 version. It works correctly

vkarpov15 commented Oct 3, 2016

Do your username and password include any non alphanumeric characters? Similar issues have surfaced in the past with handling characters like : in passwords

vkarpov15 commented Oct 3, 2016

Also, what version of mongoose and mongodb?

yankouskia commented Oct 3, 2016

Mongodb ‘v3’
No, there is no non-alphanumeric symbols.

vkarpov15 commented Oct 7, 2016

Hmm also what database is the user defined on? MongoDB users are scoped to dbs, even if they have cross-db privileges, so if the user you have isn’t defined on db you’ll need to put something like mongoose.connect(‘mongodb://$:$@$/$?authSource=admin’) if the user is defined on the ‘admin’ db.

Also, if you’re on mongodb 3.x, you might be using SCRAM-SHA-1 auth or not. Try both of the below:

  • mongoose.connect(‘mongodb://$:$@$/$?authMechanism=SCRAM-SHA-1′)
  • mongoose.connect(‘mongodb://$:$@$/$?authMechanism=MONGODB-CR’)

yankouskia commented Oct 7, 2016 •

@vkarpov15, Yes, it helped! Thank you very much!

AlexeyRomanchenko commented Oct 19, 2017 •

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 .

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.

xiaoxiekeke commented Feb 8, 2018

i tryed it , but not work,

mongoose v4.5.3
mongodb v3.4.7

errMsg:
MongoError: Authentication failed. 14|gougouS | at Function.MongoError.create (/www/website/gougouServer/source/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:31:11)

alikarimii commented Apr 21, 2018

just add ?authSource=yourDB&w=1 to end of db url

mongoose.connect(‘mongodb://user:password@host/yourDB?authSource=yourDB&w=1’)
this work for me . &w=1 is important

phamthephuc commented Jan 11, 2019

just add ?authSource=yourDB&w=1 to end of db url

mongoose.connect(‘mongodb://user:password@host/yourDB?authSource=yourDB&w=1’)
this work for me . &w=1 is important

Thank you sir. :3 good answer

Footer

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Fixing `Error: Authentication failed.` on a previously perfectly running MongoDB server

wafrat

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:

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:

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:

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:

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.

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.

Источник

Troubleshoot Connection Issues

This page outlines common connection issues and possible resolutions.

To learn more about connecting to an Atlas cluster, see the Get Started with Atlas tutorial.

If you are an enterprise customer looking for support, file a ticket . For community support, visit Community Support Resouces .

Serverless instances don’t support connecting via certain drivers or driver versions at this time. To learn more, see Serverless Instance Limitations .

Database deployment Connect button is disabled

Your database deployment’s Connect button may be disabled if your database deployment is in the provisioning state. Your database deployment needs to provision when it is first deployed. Clusters also must provision when you scaled them up or down. The provisoning process can take up to 10 minutes, after which the Connect button will become enabled.

Connecting IP address not in IP Access List

Before connecting to your Atlas database deployment, check that you added your host’s IP address to the IP access list for your database deployment’s project. Atlas allows client connections only from IP addresses and CIDR address ranges in the IP access list.

Authentication to the database deployment failed

To connect to Atlas , you must authenticate with a MongoDB database user. To create a database user for your database deployment, see Configure Database Users .

Possible solutions

If you have created a user and are having trouble authenticating, try the following:

Check that you are using the correct username and password for your database user, and that you are connecting to the correct database deployment.

Check that you are specifying the correct authSource database in your connection string.

If you have a special character in your password, see Special characters in connection string password .

Too many open connections to your database deployment

Atlas sets limits for concurrent incoming connections to a database deployment. For clusters, this is based on the cluster tier. If you try to connect when you are at this limit, MongoDB displays an error stating connection refused because too many open connections .

For a detailed comparision of cluster tiers and their maximum concurrent connections, see Connection Limits and Cluster Tier .

Possible solutions

Close any open connections to your database deployment not currently in use.

Scale your cluster to a higher tier to support more concurrent connections.

Restart your application.

To prevent this issue in the future, consider using the maxPoolSize connection string option to limit the number of connections in the connection pool.

To learn how to fix this issue, see Fix Connection Issues .

Attempting to connect from behind a firewall

Connecting to the Atlas UI

Atlas uses a CDN to serve content quickly. If your organization uses a firewall, add the following Atlas CDN host to the firewall’s allow list to prevent issues accessing the Atlas UI: https://assets.mongodb-cdn.com/ .

Connecting to a Database Deployment

Atlas database deployments operate on port 27017 . You must be able to reach this port to connect to your database deployments. Additionally, ensure that the appropriate ports are open for the following:

For sharded clusters, grant access to port 27016.

For BI Connector, grant access to port 27015.

You can check your ability to reach a port using the third-party Outgoing port tester .

Example

To check your ability to reach port 27017, visit http://portquiz.net:27017 .

If you can’t access these ports, check your system firewall settings and ensure that they are not blocking access to these ports.

Database Deployment Availability

If you are using a mongodb+srv:// connection string and your driver or shell can’t find the DNS host of the Atlas database deployment, the database deployment might be paused or deleted. Check that the database deployment exists. If this is a paused cluster, you can resume the cluster if necessary.

Atlas automatically pauses idle M0 clusters after 60 days with no connections.

MongoDB Compass Troubleshooting

If you use MongoDB Compass to connect to your cluster and experience issues, see:

Compass Connection Errors in the MongoDB Compass documentation.

If you use a self-managed X.509 certificate or an auto-generated X.509 certificate managed by Atlas to authenticate to the MongoDB database, when you connect to MongoDB Compass , you must:

In MongoDB Compass , choose Fill in connection fields individually .

In the Authentication dropdown, select X.509 .

Select More Options .

In the SSL dropdown, select Server and Client Validation .

Add the same path to the downloaded Atlas -managed certificate, or the self-managed certificate (depending on which you use) to each of these fields: Certificate Authority , Client Certificate , and Client Private Key .

To learn more, see Connect to MongoDB in the MongoDB Compass documentation.

Connection String Issues

Incorrect Connection String Format

The connection string format you use to connect to Atlas depends on several factors, including:

Your mongosh version. To learn more, see Connect via mongosh .

Your driver version. To learn more, see Connect via Your Application .

Verify your connection string in a test environment before putting it into production.

Special Characters in Connection String Password

If your password includes special characters, and you are using your password in a connection string URI, encode the special characters.

The following characters must be converted using percent encoding

if included in a username or password:

For example, if your password in plain-text is p@ssw0rd’9′! , you need to encode your password as:

вћ¤ Use the Select your language drop-down menu to set the language of the encoding example in this section.

Important

Do not encode special characters in your password if you are using your password outside of a connection string URI (for example, pasting it into mongosh ).

Connection String Incompatible with Driver Version

If you see this error message, your driver is likely out of date. For instructions on updating your driver, refer to your specific Driver Documentation .

Internet Service Provider DNS Blocks Connection String

When you use the DNS seed list connection string format to connect to Atlas , you might see the following error:

This error may occur when using the default DNS server that your ISP provides. That DNS server might not support SRV lookups that the DNS seed list connection string format uses.

To resolve the issue, you can try changing your DNS configuration to use a public DNS server .

Example

You can configure your network settings to use Google Public DNS

instead of your ISP ‘s DNS servers.

After you update your network settings to use a public DNS server, connect to the database deployment .

Connection String Error with DB Tools on Ubuntu 18.04

If running Ubuntu 18.04 and using the DNS seed list connection string format ( mongodb+srv:// ) to connect to Atlas from one of the MongoDB Database Tools ( mongodump , mongorestore , etc), you might see the following error:

If so, use one of the following connection options instead:

use the —uri option with a non-SRV connection string ( mongodb:// ).

use the —host option to specify the host to connect.

Connection Refused using SRV Connection String

When using the DNS seed list connection string format ( mongodb+srv:// ) with a driver or Compass, you may receive in the following error:

To remedy this issue, use the Standard Connection String format with Compass or that driver. With Compass, don’t set the SRV Record value, set the Hostname and Port values instead.

Источник

Понравилась статья? Поделить с друзьями:
  • Mondial forni коды ошибок
  • Monast error module twisted not found
  • Mom exe ошибка инициализации платформы net framework как исправить
  • Mom exe net framework initialization error что делать
  • Mohw exe системная ошибка msvcp100 dll windows 10