Grails - Connect to a MongoDB database using authentication - mongodb

I am trying to connect to my MongoDB using authentication.
I did this on my Mongo server:
use admin
db.addUser('adminLogin','adminPassword')
db.shutdownServer()
exit
Then I started my server again issuing mongod --auth
I set my db configurations in DataSource.groovy as follows:
grails {
mongo {
host = "localhost"
port = 27017
username = "adminLogin"
password = "adminPassword"
databaseName = "my DB name"
options {
autoConnectRetry = true
connectTimeout = 300
}
}
}
I get the following error message when I start my application:
ERROR context.GrailsContextLoader - Error executing bootstraps: Error creating bean
with name 'mongoDatastore': FactoryBean threw exception on object creation; nested
exception is org.springframework.data.mongodb.CannotGetMongoDbConnectionException:
Failed to authenticate to database
Any suggestion is most welcome.
Thanks in advance.

I ran into this same issue so I can help explain how Mongo does authentication. You see what you did is you created an admin user in the admin database which is great. However you are trying to connect to "mydb" directly with the admin user which is not allowed. Sound confusing? It's because it is. To illustrate this better here is a simple exercise:
Create a user for the admin db like you have above.
exit the mongo shell
run following
mongo
use myDBname
db.auth("adminlogin", "adminpwd")
That will fail. But try this instead.
mongo
use admin
db.auth("adminlogin", "adminpwd")
use myDBname
This will work because you switched to this db with the admin context and didn't try to connect to it directly.
So all you need to do to make this work is connect directly to the DB you want and create a user right in that db like follows:
mongo
use myDBname
db.addUser("dblogin", "dbpwd")
Update your grails config file with this and I bet you it will work.
Note that just the last part is your answer and solves your problem but since I struggled with this and figured it out the hard way I think the context really helps understand mongo auth better.
Take Care

Related

cannot connect to mongo cluster - user is not allowed to do action [getLog] on [admin.]

I have created a user and added my IP to whitelist.
when trying to connect to a cluster through mongo shell, i am required to enter the following line: mongo "mongodb+srv://cluster0.****.mongodb.net/" --username --password
I have filled in credentials for username and password and replaced dbname with my database name(tried using non-existing one as well in case that was the problem). it connects to the shell, but then crashes with the following error:
Error while trying to show server startup warnings: user is not allowed to do action [getLog] on [admin.]
MongoDB Enterprise atlas-7cwf8s-shard-0:PRIMARY>
tried googling and youtubing the issue, but cannot find the match on how to fix it.
Many thanks
That message says that the shell is unable to show you server startup warnings. It's expected in Atlas environment.
Supposing that's your own cluster, then:
Check the user in Atlas > Database Access
Check the MongoDB Roles header in the table.
If it's not atlas Admin, you can't issue this command:
db.adminCommand({getLog:"startupWarnings"})
Or any admin command, which is issued or tested automatically in the connection, hence the error.
Edit MongoDB Roles to the highest privileges (atlas Admin)
But you can still work anyways.
If you're accessing someone else's cluster, then there isn't much to do.

MongoDB + Adminer

I am running a local MongoDB service on Windows using WAMP64.
I want to access the db using Adminer. I cannot get thru the login page.
It keeps saying that Database does not support password, which it does as proven by me logging into the db using MongoDB Compass with the created auth uid and pw.
I have tried Adminer 4.6.3 and 4.7.6 (lastest v)
Anyone know how to get past this? Thanks.
The code that produces this message seems to be here.
What it appears to do is:
Connect with the provided username and password.
Connect with the provided username with an empty password.
If the second connection succeeds, return the "does not support password" error.
Otherwise, presumably return the first connection.
If I try to login without a password, even if mongod was not started with --auth parameter, my login fails. So I'm not sure what setup is needed to reproduce this behavior, but I suggest:
Ensuring your mongod invocation has --auth parameter.
Ensuring you are not able to connect to your server without specifying the password (i.e., unauthenticated connection fails).
The thing you need to do is to add a user. You don't have to run mongo with authentication enabled; if you add a user adminer will accept the auth and just work. Just run mongo:
db.createUser({
... user: "admin",
... pwd: "PASSWORD",
... roles: ["readWrite","dbAdmin"]
... })
and then you'll be able to log in with adminer

I'm trying to connect to mongodb Atlas but I keep getting error and can't proceed

My error goes :
mongo "mongodb+srv://cluster0-ts5b5.mongodb.net/test" --username admin-David
MongoDB shell version v4.0.6
Enter password: Cannot get console mode 6
I meant to write password there but I can't proceed to password so I can't connect to Atlas at all. Please sort this problem!!
I ran into this same problem today, I was able to log in by including the password in the same statement where the url and username are.
So in your case try doing this:
mongo "mongodb+srv://cluster0-ts5b5.mongodb.net/test" --username admin-David --password <yourPasswordHere>
That worked for me, hopefully it helps!
MongoDB docs reference: https://docs.mongodb.com/manual/reference/program/mongo/#cmdoption-mongo-username

how can I connect to a remote mongo server from Mac OS terminal

I would like to drop into the mongo shell in the terminal on my MacBook. However, I'm interested in connecting to a Mongo instance that is running in the cloud (compose.io instance via Heroku addon). I have the name, password, host, port, and database name from the MongoDB URI:
mongodb://username:password#somewhere.mongolayer.com:10011/my_database
I have installed mongodb on my MacBook using Homebrew not because I want Mongo running on my Mac, but just to get access to the mongo shell program in order to connect to this remote database.
However, I can't find the right command to get me the full shell access I would like. Using instructions found here http://docs.mongodb.org/manual/reference/program/mongo/ (search for "remote") I am able to get what looks like a connection, but without giving my username or password I am not fully connected. Running db.auth(username, password) returns 1 (as opposed to "auth fails" when I provide incorrect username and password), but I continue to get an "unauthorized" error message when issuing the show dbs command.
You are probably connecting fine but don't have sufficient privileges to run show dbs.
You don't need to run the db.auth if you pass the auth in the command line:
mongo somewhere.mongolayer.com:10011/my_database -u username -p password
Once you connect are you able to see collections?
> show collections
If so all is well and you just don't have admin privileges to the database and can't run the show dbs
With Mongo 3.2 and higher just use your connection string as is:
mongo mongodb://username:password#somewhere.mongolayer.com:10011/my_database
Another way to do this is:
mongo mongodb://mongoDbIPorDomain:port

How do I add an admin user to Mongo in 2.6?

I upgraded from 2.4 to 2.6 and authentication broke. This tutorial seems pretty straightforward but I keep getting locked out of my own database. My situation is pretty simple, I have a single Mongo server and need one user/pwd combination to connect.
First I connect via the localhost exception as mentioned. Then I create the admin user as suggested:
use admin
db.createUser(
{
user: "myadmin",
pwd: "mysecret",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
Now it's time to add new users so to sanity check myself, I logout of the shell. Now when I type "mongo" it fails. That used to work but OK, it's not seeing a username password and I guess the localhost exception isn't there anymore so I follow the instructions outlined here:
mongo --port 27017 -u myadmin -p mysecret --authenticationDatabase admin
And I get:
MongoDB shell version: 2.6.0
connecting to: 127.0.0.1:27017/test
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
>
Any idea on how to:
Setup Mongo 2.6 so I can easily go in and out of the shell managing the databases (I would think this is the "system user administrator")
Enable a user from a remote client to connect? (Just the mongo side, no help needed with iptables ...)
Thanks!
Apparently the "system user administrator" isn't enough. Create a root user:
> db.createUser({user:"someadmin",pwd:"secret", roles:[{role:"root",db:"admin"}]})
Then add your database user:
> use some_db
> db.createUser(
{
user: "mongouser",
pwd: "someothersecret",
roles: ["readWrite"]
}
)
More details on this gist. Comments on gist and better answers on SO welcome - I'm not a sys admin
1) The role that you assign the admin user- userAdminAnyDatabase - doesn't have unlimited privileges. It's just a role that is allowed to create and manage users on any database. Apparently, by default it is restricted from executing certain commands that are not directly related to managing database users (such as fetching the startup warnings from the log, querying the server status, etc.).
You can use the 'root' role instead as Tony suggests. If you are going to use the root account to do setup and management and then just have a few basic read/write privileged accounts talking to the database, this probably makes the most sense.
2) In general, connecting on the client side just requires calling the db.authenticate() function after connecting from your client code. There are different ways to do this depending on the driver/language that you are using for a client. The node.js driver code is pretty typical: http://mongodb.github.io/node-mongodb-native/api-generated/db.html#authenticate
Even after following #Tony's method I was getting a
`com.mongodb.CommandFailureException:`
Adding
compile 'org.mongodb:mongo-java-driver:2.13.1'
in Dependency section of BuildConfig.groovy however fixed the issue.