MongoError: auth failed mongoose connection string - mongodb

I can connect to the DB through terminal, but getting this error using mongoose and gulp.
mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:246
MongoError: auth failed
My connection string is:
mongodb://usr:psw#localhost:27017/dbname
Any idea what it can be?

I installed MEAN from MEAN packaged by Bitnami for windows 7 using the following password: 123456
Syntax for connection string to connect to mongodb with mongoose module
mongoose.connect("mongodb://[usr]:[pwd]#localhost:[port]/[db]",{auth:{authdb:"admin"}});
If you don't have {auth:{authdb:"admin"}} in the connection string, you will get the following error: MongoError: Authentication failed.
JS Example: mongo-test/app.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://root:123456#localhost/test',{auth:{authdb:"admin"}});
mongoose.set('debug', true); // turn on debug

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

There is many ways to make it work. This is what worked for me [mongoose v5.9.15] :
mongoose.connect('mongodb://localhost:27017/', {
auth: {
user:'root',
password:'example'
},
authSource:"admin",
useUnifiedTopology: true,
useNewUrlParser: true
})

You might want to do something like this...
var opt = {
user: config.username,
pass: config.password,
auth: {
authdb: 'admin'
}
};
var connection = mongoose.createConnection(config.database.host, 'mydatabase', config.database.port, opt);
'authdb' option is the database you created the user under.

mongoose.connect("mongodb://[host]/[db]", { auth:{
authdb: "admin",
user: [username],
password: [pw]
}}).then(function(db){
// do whatever you want
mongoose.connection.close() // close db
})

Do you have a user set up for dbname? By default, no user is required to connect to the database unless you explicitly set one. If you haven't, you should just try to connect to mongodb://localhost:27017/dbname and see if you still get an error.

I have found the solution hier, looks like when you create an user from the mongo shell, it makes SCRAM-SHA-1 instead of MongoDB-CR. So the solution to create a new user with MongoDB-CR authentication.
MongoDB-CR Authentication failed

just make sure that your database is created.
and also if your user is not added in the admin database, then make sure to add it by putting
db.createUser(
... {user:'admin',pwd:'admin',roles:['root']}
... )

This worked for me for mongod --version = db version v3.6.13
mongoose.connect('mongodb://localhost/expressapi', {
auth: {
authdb: "admin",
user: "root",
password: "root",
}
});

mongo mongodb://usr:psw#localhost:27017/dbname
Password should be alphanumeric only
User should be also available in db 'dbname' (Note : Even if user is super admin)
With above changes it connected successfully.

mongoose.connect("mongodb://[usr]:[pwd]#localhost:[port]/[db]",{ authSource: 'admin', useNewUrlParser: true, useUnifiedTopology: true });
I was getting same error. Resolved by adding authSource option to connect function solved the issue. see above code.

The connection string will be like
mongodb://username:password#localhost:27017/yourdbname?authSource=admin

Related

Connecting to Heroku Postgres from Auth0 results in: err no pg_hba.conf entry for host, no encryption

I'm trying to connect to my PostgreSQL database hosted on Heroku through Auth0's Database Connections.
I am getting an error when I try to invoke the Get User script within Auth0's database actions:
no pg_hba.conf entry for host "xx.xxx.xx.x", user "xxx", database "xxx", no encryption
The script looks like this:
function loginByEmail(email, callback) {
const postgres = require('pg');
const conString = configuration.DATABASE_URL;
postgres.connect(conString, function (err, client, done) {
if (err) return callback(err);
const query = 'SELECT id, nickname, email FROM organizations WHERE email = $1';
client.query(query, [email], function (err, result) {
done(); // Close the connection to the database
if (err || result.rows.length === 0) return callback(err);
const user = result.rows[0];
return callback(null, {
user_id: user.id,
nickname: user.nickname,
email: user.email
});
});
});
}
Connection String:
configuration.DATABASE_URL: 'postgres://xxx:xxx#xxx?sslmode=require'
I appended sslmode=require to the end of my connection string to ensure I have a SSL connection to my database.
I have also tried changing sslmode=require to ssl=true, which results in a different error:
self signed certificate
I am unsure where to go from here, so any help would be appreciated.
You should first establish the client and specify the rejectUnauthorized flag, like so:
const client = new postgres.Client({
connectionString: conString,
ssl: { sslmode: 'require', rejectUnauthorized: false }
});
Then, instead of using your postgres to connect, use the client:
client.connect();
client.query(...);
This should solve your problem, and the connection will be encrypted. You won't, however, be protected against Man-In-The-Middle (MITM) attacks, as specified in documentation.
#Pexers solution worked for me, however, somehow it shows TypeScript error. The way I did it is just ssl: true:
const client = new postgres.Client({
connectionString: conString,
ssl: true
});

How can I set TLS for Mongoose connection

I'm trying to migrate my mongo database from Compose to IBM Cloud Databases for Mongo and in their documnetations (https://www.compose.com/articles/exporting-databases-from-compose-for-mongodb-to-ibm-cloud/): "With a new Databases for MongoDB deployment, you'll be provided with a replica set of two endpoints to connect to your database. Databases for MongoDB also uses a TLS certificate, so you'll need to configure your MongoDB application driver to accept two hosts and a TLS certificate"
How can I set the TLS certificate provided by IBM Cloud in Mongoose connection ?
Nothing I've tried worked :(
I can see my database if I'm using the IBM cli but from my node.js application I cannot connect to it
var mongoose = require('mongoose');
mongoose.Promise = Promise;
var uri="mongodb://admin:passSftgdsdfvrrdfs#host1-1231243242.databases.appdomain.cloud:32605,host2-1231243242,host1-1231243242/testDatabaseName?authSource=admin&replicaSet=replset"
myDb.db = mongoose.createConnection(uri, {
tls: true,
tlsCAFile:`076baeec-1337-11e9-8c9b-ae5t6r3d1b17` (this is the name of the certificate and is placed in the root)
// tlsCAFile: require('fs').readFileSync('041baeec-1272-11e9-8c9b-ae2e3a9c1b17') // I have also tried something like this
absolute nothing is working even the database is there
Please help me
I'm also facing same problem
this works for me
mongoose.connect(‘mongodb+srv://username:password#host/db_name?authSource=admin&replicaSet=repliasetname&tls=true&tlsCAFile=/root/ca-certificate.crt’,{some config})
Try the following:
var key = fs.readFileSync('/home/node/mongodb/mongodb.pem');
var ca = [fs.readFileSync('/home/node/mongodb/ca.pem')];
var o = {
server: {
ssl: true,
sslValidate:true,
sslCA: ca,
sslKey: key,
sslCert:key
},
user: '****',
pass: '****'
};
m.connect('mongodb://dbAddr/dbName', o)```
I did it locally, you need to install the tunnel first
$ ssh -i "IF YOU HAVE PEM.pem" -L <27017:YOUR_AMAZON_HOST:27017> <server_user_name#server_ip_OR_server_url> -N
I managed to implement it as follows
const CERTIFICATE_PATH = 'rds-combined-ca-bundle.pem'
const certificateCA = CERTIFICATE_PATH && [fs.readFileSync(CERTIFICATE_PATH)];
const sslOptions = certificateCA
? ({
ssl: true,
tlsAllowInvalidHostnames: true,
sslCA: certificateCA,
user: MONGODB_USER,
pass: MONGODB_PASSWORD,
} as ConnectionOptions)
: {};
const options: ConnectionOptions = {
...sslOptions,
};
export const connectMongoDb = async (): Promise<void> => {
await mongoose.connect('mongodb://localhost:27017/test', options);
console.log('📊 Successfully connected to the database');
};
You need to set
MONGODB_USER
MONGODB_PASSWORD

I can not connect to monogdb with mongoose when authorization enabled

I am trying to connect with MongoDB by mongoose. Everything was ok, when I was connecting with my local db where there is no authentication.
When I've tried to connect to other DB with set admin user and credentials, I've got error and I've tried various different options but without any positive result.
I use these versions:
"mongodb": "^3.3.2",
"mongoose": "^5.7.1"
And my server side technology is node.js
I've tried these options:
const connection = await mongoose.connect(`mongodb://${host}:${port}/${db}?authSource=admin`,
{ useNewUrlParser: true, useUnifiedTopology: true });
then I've tried this:
let options = {
"auth": { "authSource":"admin"},
"user": "SVSAdmin",
"pass":"8&PG2DCUuDPvy$hx",
"useUnifiedTopology": true,
"useNewUrlParser": true
};
const connection = await mongoose.connect(`mongodb://${host}:${port}/${db}, options);
and this:
mongoose.connect('mongodb://${user}:${pass}#${uri}/${db}?authMechanism=SCRAM-SHA-1')
mongoose.connect('mongodb://${user}:${pass}#${uri}/${db}?authMechanism=MONGODB-CR')
and also this:
mongoose.connect('mongodb://user:password#host/yourDB?authSource=admin&w=1')
but it does not work. My credentials are ok.
The error message is:
{
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {}
}
Maybe important thing is that I'm connecting with db by ssh
I would be grateful for any help.
If u are using ur database remotly then u can use it via IP.
db = mongodb://52.221.52.32/DataBaseName

Sails database configuration issue with postgresql

I upgrade sails to 1.0, I resolved all the other errors but not able to resolved database connection issue,
It will be really helpful if anyone can reply on this.
module.exports.datastores = {
localDiskDb: {
adapter: 'sails-disk'
},
postgreSql: {
adapter: 'sails-postgresql',
// url: 'postgresql://admin:root#localhost:5432/testdb',
// ssl: true,
host: 'localhost',
user: 'admin',
password: 'root',
database: 'testdb'
},
};
Important Error Logs
I was using password which contains %
after changing the password sails successfully connected to postgresql.
It mostly looks like bug with Sails v1 or Sails-pgsql adapter.

Unhandled promise rejection: Error: URL malformed, cannot be parsed

I am new to aws and mongodb at the same time, so I'm stuck at a very basic point in trying to connect to my mongo databse, hosted on an amazon linux ec2 instance. The reason is, I'm not able to build the path to my database.
Here is what I'm trying to use:
mongoose.connect('mongod://ec2-user#ec2-XX-XX-XXX-XXX-XX.compute-1.amazonaws.com:27017/test' )
And here is the result of my test lambda function:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: URL malformed, cannot be parsed
I'm using mongodb 3.6.5.
Mongoose 5.x supports following syntax for authorization and also make sure you have not used any special character in url like #,-,+,>
mongoose.connect(MONGO_URL, {
auth: {
user: MONGO_DB_USER,
password: MONGO_DB_PASSWORD
}
})
Or if you want to remove deprication warning Avoid “current URL string parser is deprecated"
Add option useNewUrlParser
mongoose.connect(MONGO_URL, {
auth: {
user: MONGO_DB_USER,
password: MONGO_DB_PASSWORD
},
{ useNewUrlParser: true }
})
My issue was a more simple URI issue. Since there was an # character in the mongod address.
I had to use this:
return mongoose.connect(encodeURI(process.env.DB_CONNECT)); //added ');'
If you used the following URI in your environment file for example
MongoDB://<dbuser>:<dbpassword>#ds055915.mlab.com:55915/fullstack-vue-graphql
Make sure your password inMONGOD_URI does not have a special character like #. I had used # as part of my password character and was getting the error. After I removed special characters from my DB Password, all worked as expected.
In my case the below worked fine.
Inside db.js
const mongoose = require('mongoose');
const MONGODB_URI = "mongodb://host-name:27017/db-name?authSource=admin";
const MONGODB_USER = "mongouser";
const MONGODB_PASS = "myasri*$atIP38:nG*#o";
const authData = {
"user": MONGODB_USER,
"pass": MONGODB_PASS,
"useNewUrlParser": true,
"useCreateIndex": true
};
mongoose.connect(
MONGODB_URI,
authData,
(err) => {
if (!err) { console.log('MongoDB connection succeeded.'); }
else { console.log('Error in MongoDB connection : ' + JSON.stringify(err, undefined, 2)); }
}
);
Note:
My Node version is 10.x
MongoDb server version is 3.6.3
mongoose version is ^5.1.2
I just want update the answer from #anthony-winzlet, because I have same error and I has solve with this code.
mongoose.connect(url, {
auth: {
user:'usrkoperasi',
password:'password'
},
useNewUrlParser:true
}, function(err, client) {
if (err) {
console.log(err);
}
console.log('connect!!!');
});
I just add callback and useNewUrlParser:true. I use "mongoose": "^5.2.7",.
Happy coding!
If you deployed your app to Heroku make sure you updated the Config Vars as they are in your .env file. At least, this was my case.
I know this question has accepted answer, but this is what worked for me:
I'm using Mongoose 6.0.5 and Mongodb 5.0.6, with authentication enabled and with special character (%) in the password:
mongoose.connect('mongodb://localhost:27017', {
auth: { username: "myusername", password: "mypassword%" },
dbName: "mydbname",
authSource: "mydbname",
useNewUrlParser: true,
useUnifiedTopology: true,
}, function(err, db) {
if (err) {
console.log('mongoose error', err);
}
});
Many solutions had only user and pass for auth that needed username and password instead. Also it needed dbName to get access to mydb's collections.
I have same problem but problem with password
should'nt special character
password not use like this Admin#%+admin.com wrong
password use like this Admin right
or any password you wanna use