Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails - Connect to a MongoDB database using authentication

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.

like image 990
Alexandre Bourlier Avatar asked Dec 13 '22 02:12

Alexandre Bourlier


1 Answers

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:

  1. Create a user for the admin db like you have above.
  2. exit the mongo shell
  3. 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

like image 135
Prasith Govin Avatar answered Dec 28 '22 23:12

Prasith Govin