How to use Auth in MongoDB after adding a root user - mongodb

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

Related

IntelliJ Database explorer won't work with localhost Mongo 4.4.3

I'm up-the-middle MongoDB with authentication localhost. I have the mongod configured to bind a specific user to a specific database and from the mongo shell and my Java programs, everything works great. When I log in as that user I can do all the mongo stuff on the mongo db I bound that user to.
$ mongo -u totallyLegitUser --authenticationDatabase admin
MongoDB shell version v4.4.3
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2ba7a3f6-2ca1-49b7-8241-8133ceb3d842") }
MongoDB server version: 4.4.3
> use mfg-plan;
switched to db mfg-plan
> show collections;
activity
...
When I try to set up the same user through IntelliJ's "Database" thing, the "Test Connection" says everything is fine, but I can't run any queries through the console and the "explorer" drop down thing doesn't show collections I know are in the database.
This is what shows up when I look in the console after I've try to run the db.activity.findOne(); from the cli session...
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-256, userName='totallyLegitUser', source='mfg-plan', password=<hidden>, mechanismProperties=<hidden>} com.mongodb.MongoCommandException: Command failed with error 17 (ProtocolError): 'Attempt to switch database target during SASL authentication.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Attempt to switch database target during SASL authentication.", "code": 17, "codeName": "ProtocolError"}
I have confirmed that the username, password, and database are all correct.
How do I get IntelliJ to connect to my authenticating mongos?
Problem solved. In the "Data Sources and Drivers" dialog for my mongo hosts it asks for a Database. I was giving it the database I wanted to connect to on the host (mfg-plan). What it wants is the authenticationDatabase for the host (usually 'admin'). When I change that to 'admin', all is well.

Mongoexport auth error using mechanism "SCRAM-SHA-1"

I have taken over undocumented Mongo 4.4.8 cluster (PSA). I am trying to tidy it up and test thouroughly.
An original connection string:
MONGODB_URI=mongodb://${USER}:${PASS}#10.0.0.3:27017,10.0.0.6:27017,10.0.0.2:27017/bud?replicaSet=bud-replica&authSource=admin
I have enabled localhost and socket connection. I can log in from cmdline with
mongo -u ${USER} -p ${PASS}
MongoDB shell version v4.4.8
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("492e331b-417e-458a-83c7-9db6eaae0869") }
MongoDB server version: 4.4.8
I can switch db to bud and perform the queries. But if I run just
mongo
then the authentication with the same credentials does not work:
bud-replica:PRIMARY> db.auth('admin','admin');
Error: Authentication failed.
0
I tried to search for users but shows there arent any:
bud-replica:PRIMARY> db.getUsers()
[ ]
bud-replica:PRIMARY> use bud
switched to db bud
bud-replica:PRIMARY> db.getUsers()
[ ]
This is mongod.conf security part:
security:
authorization: enabled
keyFile: "/etc/bud-rs"
Finally I need to export my data before doing experiments. Though the cmd line interface looks similar, mongoexport cannot fetch the data, regardless I set user/password or skip these arguments.
mongoexport -h localhost --db=bud -u ${USER} -p ${PASS} -c=accidents --jsonArray > accidents.json
2021-08-25T19:30:30.631+0200 could not connect to server: connection() error occured during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
mongoexport -h localhost --db=bud -u ${USER} -p ${PASS} -c=accidents --jsonArray --authenticationDatabase “admin” > accidents.json
2021-08-25T19:36:18.738+0200 could not connect to server: connection() error occured during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
root#10:~# mongoexport -h localhost --db=bud -u ${USER} -p ${PASS} -c=accidents --jsonArray --authenticationDatabase “bud” > accidents.json
2021-08-25T19:38:21.174+0200 could not connect to server: connection() error occured during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
I am really confused and I failed to find a solution on Google or SO.
Second relevant question:
If I need to create new user, shall I do it on all replicas or it is automatically synchronized?
1st update
This is the workaround, but my questions are still valid. I want to understand.
root#10:~# mongoexport --db=bud -u ${USER} -p ${PASS} -c=accidents --jsonArray "mongodb://admin:admin#10.0.0.3:27017/bud?authSource=admin" > accidents.json
2021-08-25T20:46:54.777+0200 connected to: mongodb://[**REDACTED**]#10.0.0.3:27017/bud?authSource=admin
2021-08-25T20:46:55.778+0200 [........................] bud.accidents 0/4379 (0.0%)
2021-08-25T20:46:56.497+0200 [########################] bud.accidents 4379/4379 (100.0%)
2021-08-25T20:46:56.497+0200 exported 4379 records
2nd update
bud-replica:PRIMARY> use admin
bud-replica:PRIMARY> show collections
system.keys
system.users
system.version
bud-replica:PRIMARY> db.system.users.find()
{ "_id" : "admin.admin", "userId" : UUID("769e4f5c-6f46-4153-857e-47d7d8730066"), "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "32/AP4019eome36j8n
The user credential was created in the admin database.
When connecting with the mongo shell, switch with use admin before running db.auth
The mongoexport command that worked used authSource=admin in the connection string.
Add --authenticationDatabase=admin to the other command line to direct it to use the admin database for auth as well.
whole example command as below worked for me.
Mongodb version: 5.x.x, also for Mongodb version: 8.x.x
mongodump --authenticationDatabase=admin --uri mongodb://username:password#mongodb-host/db-name?ssl=false&authSource=admin

mongoexport works but mongo shell fails on mlab

I have a mongo db setup on mlab for use with meteor running on Galaxy. I can succesfully export from this database using mongoexport on my windows 8.1 64-bit laptop. I also want to connect with the mongo shell, but I get "not authorized" error messages, using the exact same mongo user and password.
In more detail - this works just fine, using mongoexport version r3.4.7:
mongoexport --host ds121225.mlab.com:21225 -d quarule-db01 --collection Quarule -u xxxxx -p xxxx -q "{vocabularyName: 'qre'}" --out QRE.json
while this fails:
mongo ds121225.mlab.com:21225/quarule-db01 -u xxxx -p xxxxx
MongoDB shell version v3.4.7
connecting to: mongodb://ds121225.mlab.com:21225/quarule-db01
MongoDB server version: 3.4.9
rs-ds121225:PRIMARY> show dbs
2017-10-30T19:50:37.795-0700 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode#src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs#src/mongo/shell/mongo.js:62:1
shellHelper.show#src/mongo/shell/utils.js:769:19
shellHelper#src/mongo/shell/utils.js:659:15
I have checked and rechecked that I am specifying the userid and password the same way in both commands.
Why would the export succeed and the shell fail?

Create user -- MongoDB

I'm trying to create a mongoDB user on a DigitalOcean droplet. I tried a lot of combinations, but basically, I can't make this work.
To start the service, I use mongod --noauth. Below is the command I used:
use admin
db.createUser( { user: "userhere", pwd: "passhere", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
I restarted the service and tried to connect using:
mongo admin --port 61370 --host <host> -u userhere -p
Enter password:
2015-01-21T13:30:17.279-0500 Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 } at src/mongo/shell/db.js:1210
exception: login failed
It doesn't connect.
Does anyone know the step-by-step on how to create a user on MongoDB?
You must create the user with the appropriates privileges. So you should connect to your mongo instance with :
mongo -u siteUserAdmin -p password
See the documentation as well : http://docs.mongodb.org/manual/tutorial/add-user-to-database/
Try specifying -authenticationDatabase option
mongo -u mongoadmin -p password -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)