27

I've tried this and it's not working.

I have the following error with Mongodb + Atlas:

MongoError: bad auth Authentication failed.
    at /Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/auth/auth_provider.js:46:25
    at /Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/auth/scram.js:215:18
    at Connection.messageHandler (/Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/connection/connect.js:334:5)
    at Connection.emit (events.js:203:13)
    at processMessage (/Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/connection/connection.js:364:10)
    at TLSSocket.<anonymous> (/Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/connection/connection.js:533:15)
    at TLSSocket.emit (events.js:203:13)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:276:11)
    at TLSSocket.Readable.push (_stream_readable.js:210:10)
    at TLSWrap.onStreamRead (internal/stream_base_commons.js:166:17) {
  ok: 0,
  errmsg: 'bad auth Authentication failed.',
  code: 8000,
  codeName: 'AtlasError',
  name: 'MongoError',
  [Symbol(mongoErrorContextSymbol)]: {}

Here's how I instantiate my DB:

From the credentials.js:

const config = {
    mongoConnectionURL: "mongodb://cyruslk:<MY_PASS_HERE>@franklinford-shard-00-00-3dveb.mongodb.net:27017,franklinford-shard-00-01-3dveb.mongodb.net:27017,franklinford-shard-00-02-3dveb.mongodb.net:27017/test?ssl=true&replicaSet=FranklinFord-shard-0&authSource=admin&retryWrites=true&w=majority",
    mongoDatabaseName: "FranklinFord",
  }

From my main server.js app:

const {MongoClient} = require("mongodb");
const connectionURL = config.mongoConnectionURL;
const databaseName = config.mongoDatabaseName;


  let sendToDb = (dataToInsert) => {
    MongoClient.connect(connectionURL, {
      useNewUrlParser: true,
    }, (error, client) => {

      if(error){
        console.log(error);
        return console.log("Unable to connect to the db.");
      }
      const db = client.db(databaseName);
      console.log(db);

      db.collection("ford_twitter").insertOne({
        masterData: dataToInsert
      }, (error, result) => {
        if(error){
          return console.log("unable to insert users");
        }
        console.log("Data successfully inserted");
      })
    })
  }

You can find the code here

Thanks for helping me. I have no idea what's happening.

cyruslk
  • 839
  • 3
  • 13
  • 25
  • first thing I would try is run `mongo yourfullconnectionstring` from terminal. This will tell you if problem is with code or setup – Ashish Modi Feb 01 '20 at 19:31
  • I hope you saw this note? `If the username or password includes the at sign @, colon :, slash /, or the percent sign % character, use percent encoding.` – Matt Clark Feb 01 '20 at 19:35
  • @MattClark I saw - but my password does not includes any of these – cyruslk Feb 01 '20 at 22:50
  • Does this answer your question? [Error Message: MongoError: bad auth Authentication failed through URI string](https://stackoverflow.com/questions/55695565/error-message-mongoerror-bad-auth-authentication-failed-through-uri-string) – Valijon Feb 01 '20 at 23:47
  • @Valijon no, I'm sure it's the right password and this password is the one I use for the account – cyruslk Feb 01 '20 at 23:58

28 Answers28

44

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 :)

Good luck!

enter image description here

IndustryDesigns
  • 1,938
  • 2
  • 12
  • 22
43

I had same problem, in that connection string it was written "mongodb+srv://<username>:<password>@cluster0.4h226.mongodb.n..." and you are supposed to enter username and password in that string.

  1. suppose my username is "user" and password is password, we are supposed to write "mongodb+srv://user:password@cluster0.4h226.mongodb.n...", without "<" and ">";

  2. If there are any special characters in your password, replace them with their ascii code preceded by the % sign. For example, # would be %35.

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Nikhil Thorat
  • 446
  • 6
  • 3
  • Thank you, fixed it in the meantime but it took me a while to understand. – cyruslk Nov 16 '20 at 17:20
  • You need to url encode it using `urllib.parse.quote("username@gmail.com")` and `urllib.parse.quote("p@ssword")`. Check this answer here https://stackoverflow.com/a/39283299/337666 – Shrikant Prabhu Dec 18 '20 at 06:46
8

I faced the same problem I have changed the password but it didn't work. My Password includes numbers I removed them and it worked

Daniya Niazi
  • 180
  • 3
  • 10
1

This is Not Always Only About The Password

Though your error already answered by some people which was a password issue. However, looking at the comments and answer here, I see a lot of people having similar error but unable to solve with the provided answer. But why ?

This error is not only about the password. Here Database Name, Password and Username do matter.
Since Database name, Password and Username are part of the url, therefore if you use any special character in any of these three part of your url, then you need to replace them with % and then ASCII Code of those special sign. For example: for $- sign you need to replace it with %36%45
And obviously remove < and > sign also from the initial link you copied which is like <password>.
See ASCII Code Here
See the image to understand more

M_Yeasin
  • 46
  • 4
1

First, the error MongoServerError: bad auth: Authentication failed indicates username and password may be incorrect.

Solution: In credential.js remove the brackets <> around username and password then you have a database connection.

Ken Mwangi
  • 11
  • 3
1

After lots of headache searching for the answer, I realize that my in the connection stream still had the <> around the password. Make sure to remove this.

JavaEddie
  • 31
  • 1
1

I also facing the same issue and I removed +srv and it worked for me.

Suyash
  • 29
  • 7
0

Also try it as,

'CLIENT' : { 'host' : 'connection_string_to_mongodb' }

since, connection_string has username, password, database name, clustername and so, just have this one key-value pair in the client. It worked for me.

mananbh9
  • 541
  • 4
  • 3
0

Also make sure your password does not have any numbers or special characters

xi_darius
  • 104
  • 9
0

Might as well try to add your IP to the white list. Go to Network Access -> Add IP Adress -> Current IP, then save changes and try again, hope it'll help.

Slava.In
  • 597
  • 1
  • 9
  • 22
0

making a new admin user account worked for me. i found this was not only case with pymongo but also when I was working with mongo shell.

0

the solution is to remove brackets <> from the user name and password. enter the correct database name. Give access to your database so that the data is posted into your database.

0

The solution for this is make sure you username and password should include '_' between name and number if in case your name or password includes number

0

Use this

const config = {
    mongoConnectionURL: "mongodb://cyruslk:MY_PASS_HERE@franklinford-shard-00-00-3dveb.mongodb.net:27017,franklinford-shard-00-01-3dveb.mongodb.net:27017,franklinford-shard-00-02-3dveb.mongodb.net:27017/test?ssl=true&replicaSet=FranklinFord-shard-0&authSource=admin&retryWrites=true&w=majority",
    mongoDatabaseName: "FranklinFord",
  }

NOTE:

remove '<' & '>' from the username and password and make sure that the username and password lies just before and after the colon (symbol = ":" ) there should be no empty space before and after the colon

0

For me, I solved this by creating another admin user. I forgot that I have a deployed web app that is already using an admin user. So creating another admin user and use it as a Mongo URI on a different web app helped solve me this authentication issue

leipzy
  • 11,676
  • 6
  • 19
  • 24
0

If you are using dotenv then first make sure you have installed it and called it from index.js page require('dotenv').config();

Then the most uncommon mistake might be Creating a variable named "USERNAME" in the .env file.

//Do not create a variable named USERNAME=abc in the .env file 
0

Use ${password} instead of <password> in code

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
mia
  • 1
  • 1
    Your answer could be improved by providing an example of the solution and how it helps the OP. – Tyler2P Jun 17 '22 at 16:02
0

Have tried all listed solutions and nothing worked except for "Removing numbers from password" from database cluster. And it worked.

ant_dev
  • 653
  • 8
  • 16
0

check your username and password of your database created NOT from you network.

like this

           username    password                                 name of ur database                 

mongodb+srv://eshop1235:benonti1244$$@cluster0.4nzfbwx.mongodb.net/eshop-database?retryWrites=true&w=majority

all of these answer u will find in:

right navigation:

security

 quickstart

 database access

 network access

the ooptions edit.

enter image description here

before doing it, please check whether ur databased is "active".

enter image description here

enter image description here

0

I had the same issue and what worked for me was changing my user's name, from yazi-kun to yazikun I believe that your username should not contain space or any special character

  • Yes, as you said if user name or password contains special characters then you need to replace them with their ascii code after % sign. For example $ would be %36. – Temuujin Dev Nov 25 '22 at 18:14
0

I had the same issue. I created a new cluster, and the problem is solved.

0

The allowed special characters was where I was going wrong. If you enter your password in the connection URL exactly how you entered it in your account and include some of the characters contained here, it will not work.

cfynes
  • 63
  • 4
0

In my case I was putting the DB_URL inside the doten (.env file), and by mistake I put the DB_URL like this:

DB_URL = "mongodb+srv://USERNAME:<password>@cluster0.8v3jxwm.mongodb.net/?retryWrites=true&w=majority"

And this is a mistake, we do not must add a string quotation here, it must be like this:

DB_URL = mongodb+srv://USERNAME:<password>@cluster0.8v3jxwm.mongodb.net/?retryWrites=true&w=majority
Amir
  • 349
  • 3
  • 4
0

Double check that your IP is 'whitelisted' on your MongoDB Atlas "Network Access" settings, or use the 'access from anywhere' option, which is: 0.0.0.0/0 (includes your current IP address).
    I don't know if this will help anyone: for me, I was starting my server via: node app.js
I did npm start instead (my package.json reads: "start": "node server/app.js") and my connection went through.
Perhaps running the server without npm, the .env file was not being recognized, I honestly have no idea but it worked.

-1

I faced the same problem and found the solution. but changed the database password and it works. [try to keep the auto-generated password]

  • you can change the password from the Database Access sections of MongoDB. and try to keep auto-generated password. – Arijit Das Jun 12 '21 at 02:53
-1

I solved the same issue on my web app by following the percent encoding (sometimes called URL enconding), which is a way to encode characters that have specific meaning in this type of context. The encoding consists of substitution of the special characters; for example: A '%' followed by the hexadecimal representation of the ASCII value of the replace character, as explained here.

plain-text part is: ! you need to encode it as: %21

mrb
  • 39
  • 8
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/34409631) – esqew May 21 '23 at 22:13
-1

I tried everything in this thread and other threads including changing my password, adding another user, trying another collection, and could not figure this out after wasting hours. Very frustrating - I ended up switching to CouchDB because at least I could do this very basic thing with no issues.

user2859829
  • 125
  • 2
  • 8
-2
pip install djongo
pip install dnspython
DATABASES = {
    'default': {
        'ENGINE': 'djongo',
         "NAME": "database name",
        "CLIENT": {
        "host": "connection_string_to_mongodb",
        
    },
        
    }
}

the above code worked for me. separately providing username and password didn't work

dattamks
  • 9
  • 1
  • 1