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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With