Log in to mongo shell without declaring authentication DB - mongodb

Is it possible to login on mongo shell without declaring the authentication DB? Here's an example, i log in to our mongo server using this command
[localhost$] mongo servername:27117 -u username -p passwd admin
Is there a way to log in without explicitly adding the admin db on the command?

Each user is associated with an authentication database. So if your user is declared in admin database (and authorization activated, what MUST be done in all environment server), it's mandatory to add this param in your login command.
See authentication, and more generally security for more details and explanations.
EDIT
In case of using Connection String URI Format, you can skip authentication database param, in this case 'admin' will be used by default for authentication database, and 'test' by default as target database.
Example : (your user is created in 'admin' database.)
Here's different behaviors :
authentication against 'admin', database targeted is 'test'
$ mongo --host mongodb://user:pwd#myhost:27000
$ mongo --host mongodb://user:pwd#myhost:27000/test?authSource=admin
$ mongo --host mongodb://user:pwd#myhost:27000/?authSource=admin
authentication against 'admin', database targeted is 'admin'
$ mongo --host mongodb://user:pwd#myhost:27000/admin
$ mongo --host mongodb://user:pwd#myhost:27000/admin?authSource=admin
authentication against 'test', database targeted is 'test' (will not succeed)
$ mongo --host mongodb://user:pwd#myhost:27000/test
$ mongo --host mongodb://user:pwd#myhost:27000/test?authSource=test
EDIT 2
As you really need to use mongo -h -u -p notation, create your user in your 'test' database, which will be used by default in this case :
this will authenticate against 'test' database, and target 'test' database
mongo -h 199.99.99.99:27000 -u user -p pwd

Related

MongoExport SASL authentication step: Authentication failed

I am having trouble running the mongoexport on my server in regards to the error SASL authentication step: Authentication failed.
The command i'm using is:
mongoexport --db database --collection users --out /var/www/test.json -u username -p password --authenticationDatabase 'database'
I am able to get into mongo using this command:
mongo -u username -p password -authenticationDatabase database`
When I go into the user roles, my user has "ReadWrite" access.
I've tried adding role "backup" to the user, but always receive the error
"No role named dbAdminAnyDatabase#database"
"No role named backup#database"
I'm using Mongo version 3.4.6.
Can anybody help me? What am I doing wrong?

How to get backup with mongodb

When I want to take a back up I confront to this command
mongodump -d databasename -u admin -p -o /home
I encounter an error Errmsg: "auth faild",code:18}
But with this user and pass I can connect to database
But while I would prefer to disconnect authentication
I will Get backup
Thanks
This message indicates that mongodump couldn't authenticate against the mongod. There are a few possible causes. Looking at the docs we can see the following note about the -p option.
Changed in version 3.0.0: If you do not specify an argument for
--password, mongodump returns an error.
Changed in version 3.0.2: If you wish mongodump to prompt the user for
the password, pass the --username option without --password or specify
an empty string as the --password value, as in --password "" .
In the example command you provided, there is just a -p which means it is expecting a password.
Additionally, the --authenticationDatabase option is missing. Looking at the docs for mongodump:
Specifies the database in which the user is created. See
Authentication Database.
If you do not specify an authentication database, mongodump assumes
that the database specified to export holds the user’s credentials.
If you do not specify an authentication database or a database to
export, mongodump assumes the admin database holds the user’s
credentials.
Since the -d parameter is specified, mongodump will try to authenticate against that database. It is more likely that the user exists in the admin database.
Taking all of this into account, please try the following command:
mongodump -d <databasename> -u <user> --authenticationDatabase admin -o /home
This command will prompt you for a password via stdin. If you want to specify the password on the command line, the command changes to
mongodump -d <databasename> -u <user> --authenticationDatabase admin -p <password> -o /home
Please replace <databasename>, <user>, and <password> with the appropriate values for your environment.

Use mongorestore to restore a database to MongoDB (3.4) with --auth enabled, SASL error

Using mongorestore, I am trying to restore a MongoDB database to a new server (both version are 3.4). The new server has -auth enabled, so you are required to login. The database does not exist so I want mongorestore to create it using the --db option. This works when authorization is not enabled but if I enable authorization the restore fails with the following error:
Failed: error connecting to db server: server returned error on SASL authentication step: Authentication failed.
I am using an admin account with the root role when I attempt the restore.
Backing up prod and restoring to dev is a fairly regular activity for us, but we can't just drop the existing database and recreate it because of the error above, not unless we disable authorization which doesn't make much sense. Is there a better way to do this/avoid the SASL errors/not have to disable auth?
I was getting the same error and while I couldn't figure out what was wrong restoring with my admin user (my hunch is a ! in the password which escaping did not help) I was able to restore by creating a new user specifically for the role.
In mongo shell:
>use admin;
>db.createUser({
user: 'restoreuser',
pwd: 'restorepwd',
roles: ['restore']
});
In terminal:
$mongorestore --host databasehost:12345 --username restoreuser --password restorepwd --authenticationDatabase admin --db targetdb ./path/to/dump/
Thanks to Adamo Tonete over at Percona, he helped us solve this problem. If you want to restore a database using your admin user with the root role, you need to specify the authentication database and user in the mongorestore command.
mongorestore --host hostname:27017 -u adminuser -p pass --authenticationDatabase admin -d TargetDatabase /Data/TargetDatabaseRestore
That tells mongo to use the admin database to authenticate the user you are passing in. If that user has the correct rights assigned, it will be able to create the new database.
First Access your db to 4366 port then run this command
mongorestore --port 4366 -u admin -p password --authenticationDatabase admin -d dealmoney /home/yash/Desktop/prodDump/teatingToProductionLastDump/dealmoney .

Connect to a specific database by default in mongodb

I am running a mongodb on a linux box. So every time I connect to it from the console (typing mongo) I get something like this:
MongoDB shell version: 2.4.9
connecting to: test
And then I am doing use myDatabase (where myDatabase is 99% is the same). So basically I always do some unneeded type of work. Is there a way to configure mongo, so that it will connect to myDatabase by default?
Surprised that I don't find a duplicate of this. Okay, now we have content.
From the command line, just do this:
$ mongo myDatabase
This actually is covered in the documentation, albeit down the page somewhat. No direct link but search for <db address> and the same example is there.
Of course you could have done:
$ mongo --help
MongoDB shell version: 2.4.9
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.169.0.5/foo foo database on 192.168.0.5 machine
192.169.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999
Which shows the usage along with other options you can pass in.
Another thing, not quite a default connect but a shortcut is you can do this in the .mongorc.js file:
db=db.getSiblingDB("myDatabase")
Which assigns the variable db to that database so now:
db.collection.find()
Is acting on myDatabase.
As per latest mongodb drivers, we can provide default database name in connection string like this:
1. Connect using the mongoShell
mongo "mongodb+srv://sandbox.ununu.mongodb.net/mydatabase" --username user001
2. Connect using the drivers
mongodb+srv://user001:<password>#sandbox.ununu.mongodb.net/mydatabase?retryWrites=true&w=majority
Details of parametere:
Replace mydatabase with the name of the database that connections will use by default.
sandbox.ununu.mongodb.net is your cluster name
You will be prompted for the password for the Database User,user001.
user001 is username
For more details on passing ReplicaSet, other query string parameters, etc. refer mongodb official document. document link
Usually mongodb connects to default database test. It's very simple connect to any database, we just need to specify the new database name in the mongo shell
With authentication enabled and enter password on runtime (preferred mostly)
mongo --port 27017 -u USERNAME DATABASE_NAME --authenticationDatabase admin
With authentication enabled and password supplied on shell (not recommended)
mongo --port 27017 -u USERNAME -p PASSWORD DATABASE_NAME --authenticationDatabase admin
With authentication disabled
mongo --port 27017 -u USERNAME -p PASSWORD DATABASE_NAME
The above commands will directly connect to the database which we have specified.
Note: make sure the user has the necessary privilege to perform the operations
mongosh
use admin
db.createUser({ user: "user" , pwd: "1234", roles: [ "readWrite", "dbAdmin" ] })
use metadata
db.createCollection("product")
// mongodb://user:1234#localhost:27017/metadata

How do I create a new MongoDB from the command line with auth turned on?

For the purpose of wanting to create a MongoDB database in a Capistrano task, I need to figure out how to create a new database via the MongoDB shell when MongoDB is running with auth turned on.
With auth turned on the MongoDB shell can't do anything without first authenticating, but authenticating has to happen while using the admin database as far as I'm aware. So I've been connecting to it for starters like:
sudo -u mongodb mongo admin --eval "db.auth(username, password)"
And that authenticates me for further action but...at that point I need to create the database, and a user for it in the same shell session. I can't however:
sudo -u mongodb mongo admin --eval "db.auth(username, password);use new_database"
Because use database can't be used in eval. So I've tried instead:
sudo -u mongodb mongo admin --eval "db.auth(username, password);db = connect('localhost:27017/new_database')"
And that will actually get me an instance of the new database I want created but if I try to:
sudo -u mongodb mongo admin --eval "db.auth(username, password);connect('localhost:27017/new_database').addUser(new_user, new_password)"
I get an authentication error, so apparently using the connect() command forgets that I've authenticated before.
So this is where I'm stuck, trying to create a database in one line with MongoDB using auth and an admin user.
Any suggestions on how I can do this?
You can use db.getSiblingDB(name) to reference the new database and add a new account, eg:
mongo -u username -p password admin --eval "db.getSiblingDB('new_database').addUser('new_user', 'new_password');"
Now you should be able to authenticate from the command line using -u and -p:
mongo -u new_user -p new_password new_database
Beware of the fact that addUser function got deprecated since version 2.6.
Use db.createUser() and db.updateUser() instead of db.addUser() to add users to MongoDB.
Your code should be like below :
mongo -u username -p password admin --eval "db.getSiblingDB('new_database').createUser({ user : 'new_user', pwd : 'new_password', roles : [{ role: 'readWrite', db: 'new_database'}]});"