Authenticate in MongoDB - mongodb

when setup mongodb, i has been created admin account:
use admin
db.createUser(
{
user: "demo",
pwd: "demo",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
but when connection database using java:
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("mydb");
String username = "demo";
String password = "demo";
boolean auth = db.authenticate(username, password.toCharArray());
System.out.println(auth);
result false, somebody can help me???

See the link for procedure of authentication done in mongodb Enable Client Authentication, may be you missed the first step, hope it helps you.

Related

TypeORM in NestJS can not connect to MongoDB

I install the mongodb software on my own Ubuntu server and I get the mongo string just like this mongodb://xxx:pass#42.212.159.109:27017,when I type this string in my local terminal and use mongosh mongodb://xxx:pass#42.212.159.109:27017, it works fine and the connection is success. But when I use this mongodb string in my nestjs project, when I run npm run start, the terminal output MongoServerError: Authentication failed.
app.module.ts
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => {
const username = configService.get('MONGO_USER');
const password = configService.get('MONGO_PASS');
const database = configService.get('MONGO_DATABASE');
const host = configService.get('MONGO_HOST');
const port = configService.get('MONGO_PORT');
return {
type: 'mongodb',
host,
port,
username,
password,
database,
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
};
},
The mongodb version is 4.1.3, TypeOrm version is 0.2.38.
Does anyone know what is the problem and how to solve it? Thank u.
I have figure out what the problem is, as the authSource of my mongodb is not the same one with the database to save data. So I should set the authSource option to admin, then it works.
return {
type: 'mongodb',
host,
port,
username,
password,
database,
authSource: 'admin',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
};
Maybe you should try to use the Database URL connection string instead of host, port, username, password, ...
So instead of using this
return {
type: 'mongodb',
host,
port,
username,
password,
database,
entities: ...
...
}
you should use this
return {
type: "mongodb",
url: configService.get("DATABASE_URL"),
entities: ...
...
}

How do I connect to a MongoDB Database using SSL with Loopback

I am trying to connect to a MongoDB Database in Rackspace w/ SSL using loopback, but it's not working. It seems to connect fine; if I enter wrong credentials (on purpose) I get an error message saying "Can't connect", but when I use the correct credentials no error shows so I THINK I'm connecting fine. But when I try to query the database it always timesout, any idea whats happening?
My datasources.json looks something like:
"db": {
"name": "mongodb",
"url": "mongodb://username:password#iad-mongos2.objectrocket.com:port/dbName?ssl=true",
"debug": true,
"connector": "mongodb"
}
I keep reading things about needing a certificate file, but not sure if that applies in this case.
Any help would be greatly appreciated!
use datasources.env.js as below
var cfenv = require('cfenv');
var appenv = cfenv.getAppEnv();
// Within the application environment (appenv) there's a services object
var services = appenv.services;
// The services object is a map named by service so we extract the one for MongoDB
var mongodb_services = services["compose-for-mongodb"];
var credentials = mongodb_services[0].credentials;
// Within the credentials, an entry ca_certificate_base64 contains the SSL pinning key
// We convert that from a string into a Buffer entry in an array which we use when
// connecting.
var ca = [new Buffer(credentials.ca_certificate_base64, 'base64')];
var datasource = {
name: "db",
connector: "mongodb",
url:credentials.uri,
ssl: true,
sslValidate: false,
sslCA: ca
};
module.exports = {
'db': datasource
};
http://madkoding.gitlab.io/2016/08/26/loopback-mongo-ssl/
https://loopback.io/doc/en/lb3/Environment-specific-configuration.html#data-source-configuration
Create a Datasource using lb4 datasource command, edit the datasource generated by adding the SSL details to the config object: 'ssl', 'sslvalidated', 'checkserverIdentity, sslCA, sslKey etc.
import fs from 'fs';
import path from 'path';
const ca = fs.readFileSync(
path.join(__dirname, '../../utils/certs/mongodbca.cert'),
'utf8',
);
const config = {
name: 'test_db',
debug: true,
connector: 'mongodb',
url: false,
host:'hostname',
port: port,
user: 'user',
password: 'password',
database: 'databasename',
authSource: 'admin',
useNewUrlParser: true,
ssl: true,
sslValidate: true,
checkServerIdentity: false,
sslCA: [ca],
};
This worked for me, You can monkey patch the Mongo.connect() function by which you can add the option parameter.
Make a boot script file which can use the MongoDB option parameters of SSL certificate to make a secured connection to MongoDB, below code snippet, is written in a boot script js.
//Below code is written in a boot script
var monog_cert_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/mongodb.pem'));
var monog_ca_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/rootCA.pem'));
var monog_key_file = fs.readFileSync(path.join(__dirname, '../certificate_dir/mongodb.pem'));
const mongoOptions = {
ssl: true,
sslValidate: false,
sslCA:monog_ca_file,
sslKey:monog_key_file,
sslCert:monog_cert_file,
authSource:"auth_db_name"
};
//Patching Mongo connect For option variable
const mongodb = require('mongodb').MongoClient;
const ogConnect = mongodb.connect;
const connectWrapper = function(url,cb) {
return ogConnect(url, mongoOptions, cb);
}
mongodb.connect = connectWrapper;
//Patching Mongo connect For option variable
use datasources.json as below
app_db: {
"host": "127.0.0.1",
"port": 27017,
"database": "test",
"name": "app_db",
"username": "youruser",
"password": "yourpassword",
"connector": "mongodb",
"ssl":true,
"server": {
"auto_reconnect": true,
"reconnectTries": 100,
"reconnectInterval": 1000,
"sslValidate":false,
"checkServerIdentity":false,
"sslKey":fs.readFileSync('path to key'),
"sslCert":fs.readFileSync('path to certificate'),
"sslCA":fs.readFileSync('path to CA'),
"sslPass":"yourpassphrase if any"
}
username,
password,
auto_reconnect,
tries and interval all are optional.
use below link to get the certificates using OpenSSL
https://docs.mongodb.com/manual/tutorial/configure-ssl/

Authentication error (credentials missing in user document) in Mongo 3.0.1

I am having trouble with a basic user connection to my new Mongo setup.
The error looks like this in mongo.log:
authenticate db: a { authenticate: 1, user "u", nonce: "xxx", key: "xxx" }
Failed to authenticate u#a with mechanism MONGODB-CR:AuthenticationFailed MONGODB-CR credentials missing in user document
and here is my user setup
> use a
switched to db a
> show users
{
"_id":"a.u",
"user":"u",
"db":"a",
roles:[
{
"role":"readWrite",
"db":"a"
},
{
"role":"dbAdmin",
"db":"a"
}
]
}
Id user u has readWrite on database a, why is he being rejected? All the examples I found when googling where users that were created in the wrong db.
Thanks in advance.

MongoError: auth failed mongoose connection string

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

How to change my mongoDB user password as non administrator?

I understand I can change a user's password by running db.changeUserPassword() as an MongoDB administrator. However, as a user with no administrator privilege, can I change my password just with my own account?
Thanks,
Although solution provided by Gergo worked. But I had to create a new role in order for it to work. I thought changeOwnPassword should be a built in privilege and not require additional admin work. Creating a dedicated role just for the purpose to be able to change user's own password is overkill in MongoDB.
If you have the necessary privileges, you can change your own password. You can verify that you have the necessary privileges by running this command:
db.runCommand(
{
usersInfo:"username",
showPrivileges:true
}
)
If it contains changeOwnPassword, then you can change the password:
db.runCommand(
{ updateUser: "username",
pwd: "password"
}
)
You can find more information in the MongoDB documentation.
In the admin database, create a new role with changeOwnPassword action.
use admin
db.createRole(
{ role: "changeOwnPasswordRole",
privileges: [
{
resource: { db: "", collection: ""},
actions: [ "changeOwnPassword" ]
}
],
roles: []
}
)
create a new user with changeOwnPasswordRole role and along with other roles
use test
db.createUser(
{
user:"user123",
pwd:"12345678",
roles:[ "readWrite", { role:"changeOwnPasswordRole", db:"admin" } ]
}
)
login the above user credentials
Use the below command to update own password
db.updateUser("user123",{pwd: "pass123"})