Authenticating with MongoDB from JavaScript file - mongodb

I'm trying to write a MongoDB script as part of automating customer data deletion in accordance with GDPR (current process is manual), but I'm having problems authenticating from the script. Authentication works perfectly from the command line, but not from a script.
I'm not certain which mechanism I should use, but since there are only two that don't require external files (which I don't use in the command line), I figured I'd try both.
When running from the command line, this is the command I use:
$ mongo -u [adminusr] -p '[adminpwd]' --authenticationDatabase admin
This script:
var host = '127.0.0.1';
var port = '27017';
var user = 'admin';
var pwd = 'secrets';
var authDB = 'admin';
try {
var conn = new Mongo('mongodb://' + host + ':' + port + '/' + authDB);
conn.auth({
user: user,
pwd: pwd,
mechanism: 'SCRAM-SHA-1',
digest: false
});
// deletion commands...
} catch (e) {
print(e);
}
gives this error:
$ mongo erasure.js
MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.10
Error: Authentication failed.
Changing the auth part to this:
conn.auth({
user: user,
pwd: pwd,
mechanism: 'MONGODB-CR',
db: authDB,
digest: false
});
gives me this error:
$ mongo erasure.js
MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.10
Error: auth failed
The official documentation on writing MongoDB scripts and authentication is also very scarce on how to do this.
How can I get the auth to work?
Thanks.

Related

mongodb initdb.js script fails when running "use somedbname"

When I run the following script:
mongo -u root myinitscript.js
And myinitscript.js has the following code:
use somedbname
db.createUser({
user: 'someuser',
pwd: 'somepass',
roles: [{
role: 'dbOwner',
db: 'somedbname'
}]
});
Produces the following error:
MongoDB shell version v4.4.0
Enter password:
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("352e2ff4-3c4b-4e4c-b898-b67450c13627") }
MongoDB server version: 4.4.0
uncaught exception: SyntaxError: unexpected token: identifier :
#mongodb_init.js:1:4
failed to load: mongodb_init.js
exiting with code -3
When I remove use somedbname from the script - it works, but does NOT create the database, which is my primary goal. Running use somedbname under mongo shell works just fine, but is NOT an automation.
Any hints on how to solve this?
use dbname is a special shell helper. When you load a js file you can't use this helper because its syntax is not valid js.
Use getSiblingDb instead in js files.
You can also use the connection string (mongodb:// URI) as the shell argument and include the database in the connection string.

Create a user, but then can't connect with it

I've created a new user on a clean database, but can't connect with it. I can, however, connect with no credentials.
PS C:\Program Files\MongoDB\Server\3.0\bin> .\mongo.exe localhost/test
MongoDB shell version: 3.0.11
connecting to: localhost/test
> var me = { user: 'dave', pwd: 'password', roles: [ 'userAdminAnyDatabase'] }
> use admin
switched to db admin
> db.createUser(me)
Successfully added user: { "user" : "dave", "roles" : [ "userAdminAnyDatabase" ] }
> ^C
bye
PS C:\Program Files\MongoDB\Server\3.0\bin> .\mongo.exe -u dave -p password
MongoDB shell version: 3.0.11
connecting to: test
2016-04-27T15:40:38.185+0100 E QUERY Error: 18 Authentication failed.
at DB._authOrThrow (src/mongo/shell/db.js:1271:32)
at (auth):6:8
at (auth):7:2 at src/mongo/shell/db.js:1271
exception: login failed
I believe that you are connecting to the test database. But the user was created in the admin database.
Try to create the user in test. use test.
Or specify in the login which scheme to connect to

How to use Auth in MongoDB after adding a root user

I need to connect to to my MongoDB remotely. So I've commented out the line bind_ip in the mongod.conf and set there also auth=true. Now I was able to connect remotely.
Then I typed following on the machine running mongodb:
use admin
db.addUser("myadmin", "mypw")
Was created successfully but now when I try to connect remotely or even on the local machine and I try to execute anything it sais: not authorized on admin to execute command
Even that I try to connect like this: mongo -u myadmin -p mypw (locally)
I get following error:
MongoDB shell version: 2.6.9
connecting to: test
2015-04-08T15:25:53.425+0200 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1260
exception: login failed
Maybe because he tries to connect to the test db? How can I specify which db. Remotely it doesn't work with mongo --host myurl -u myadmin-p mypw
with following error:
2015-04-08T14:31:00.373+0200 E QUERY Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 }
at DB._authOrThrow (src/mongo/shell/db.js:1236:32)
at (auth):6:8
at (auth):7:2 at src/mongo/shell/db.js:1236
exception: login failed
Please try to use --authenticationDatabase while connecting to mongo shell, like in the following:
mongo -u myadmin -p mypw --authenticationDatabase admin

MongoDB: set user/password to access to db

I'm trying to set password for mongodb to prevent access to db with empty login and pass (set by default).
I'm statring mongo server:
sudo ./mongod
Starting client:
./mongo
Setting password:
use admin
db.addUser("root", "root")
exit
The output is:
MongoDB shell version: 2.2.0
connecting to: test
> use admin
switched to db admin
> db.addUser("root", "root")
{
"user" : "root",
"readOnly" : false,
"pwd" : "2a8025f0885adad5a8ce0044070032b3",
"_id" : ObjectId("50c90b94e28c41a388104f64")
}
> exit
Hoever, wheh I try to auth with empty credentials (I use mViever admin UI), it still works. Otherwise, access with root/root is not avialable. What I'm doing wrong?
Also tried to start mongo server with -auth parameter, the same result:
./mongod -auth
UPD: After starting with -auth parameter can't login with any pass. Getting:
Thu Dec 13 03:27:38 uncaught exception: error {
"$err" : "unauthorized db:admin ns:admin.system.users lock type:1 client:127.0.0.1",
"code" : 10057
}
Update: I dont know what's goin on...
> db.auth("root","root");
1
> ^C
bye
It can login. Let's restart ./mongod --auth and ./mongo:
MacBook-Pro-Ilya:bin ilyarusanen$ ./mongo
MongoDB shell version: 2.2.2
connecting to: test
> db.auth("root","root")
Error: { errmsg: "auth fails", ok: 0.0 }
0
> db.test.insert({"yeah":"2342"})
Fri Dec 14 08:52:05 uncaught exception: getlasterror failed: { "errmsg" : "need to login", "ok" : 0 }
> use admin
switched to db admin
> db.addUser("root","root")
Fri Dec 14 08:52:14 uncaught exception: error {
"$err" : "unauthorized db:admin ns:admin.system.users lock type:1 client:127.0.0.1",
"code" : 10057
}
> db.auth("root","root")
1
Why at first it can login? Why after restarting mongo is not able to login? And why after FAILED attempt to addUser, it becomes able to login? Thanks.
UPDATE2: MongoHub seems to auth ok. However, from NodeJS I still can't login: I use such code:
mongo_db.open(function(err,data){
if(data){
data.authenticate("root", "root",function(err2,data2){
if(data2){
console.log("Database opened");
}
else{
console.log(err2);
}
});
} else {
console.log(err);
}
});
And I get:
{ [MongoError: auth fails] name: 'MongoError', errmsg: 'auth fails', ok: 0 }
But mention, MongoHub with same credentials works fine.
From your comment you mention that you are using mViewer. Version 0.9.1 of mViewer does not support authentication. According to this issue on the mViewer GitHub, this is resolved in version 0.9.2, which was targeted for release in Oct.
Before starting the node with authentication, log on to the node and add a user. Then start the node with --auth and connect to the shell without mViewer.
At this point you can connect to the admin database and authenticate your admin user:
use admin
db.auth('root', 'root')
Since you set up an admin user, which will have access to all the databases, you need to authenticate against the admin database. Once you have done this you will have access to all the databases. You will also be able to create new users on any database, or create new read only users for all the databases.
If you create a new user that has access to only one database, that user would need to use that database and db.auth(name, pass) against it.
If you create a new user that has read only access to all databases, they would use admin and then db.auth(name, pass) to gain their read only access to all databases
You can find more information on setting up authentication here and more information about setting up users here
Note: When you start a node without --auth then no authentication is enabled. This means you can connect with the shell and db.auth('root','root') but it won't do anything as far as access is concerned. MongoDB will not deny access to the databases without --auth command line option (--keyFile in sharded setups or replica sets)

MongoDB db.serverStatus() gives error when running using tunnel that is targeted to api.cloudfoundry.com

Following is the console session...
C:\Users\xxx>vmc tunnel myMongoDB
Getting tunnel connection info: OK
Service connection info:
username : uuuu
password : pppp
name : db
url : mongodb://uuuu:pppp#172.30.xx.xx:25200/db
Starting tunnel to myMongoDB on port 10000.
1: none
2: mongo
3: mongodump
4: mongorestore
Which client would you like to start?: 2
Launching 'mongo --host localhost --port 10000 -u uuuu -p pppp db'
MongoDB shell version: 2.0.6
connecting to: localhost:10000/db
> db.serverStatus()
{ "errmsg" : "need to login", "ok" : 0 }
>
Which credentials should I use to login (assuming should use db.auth) to get rid of the error "{ "errmsg" : "need to login", "ok" : 0 }".
When I run the same in micro CF on my machine it works ok and gives me the expected output.
P.S. I'm trying this to get to know the current connections on my application, written in node.js. Trying to debug some issues with connections to the DB. If there is any other alternative that I can use please suggest that as well.
this should work! Not sure why your tunnel isn't connecting, my immediate suggestion is to try another instance of MongoDB and see if the same error occurs.
If you are trying to inspect the bound services on you node.js app you should be able to inspect them in the VCAP_SERVICES environment variable. For example;
var http = require('http');
var util = require('util');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(util.inspect(process.env.VCAP_SERVICES));
res.write("\n\n************\n\n");
res.end(util.inspect(req.headers));
}).listen(3000);
This code is currently running at http://node-headers.cloudfoundry.com/ to serve as an example. However, mongodb connections for node.js applications should automatically configure to the bound service. If this does not work for you, then please do let me know.