Grails - connecting 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 by 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 } } } 

When the application starts, the following error message appears:

 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 welcome. Thanks in advance.

+4
authentication database mongodb grails database-connection
source share
1 answer

I ran into this problem, so I can explain how Mongo performs authentication. You see what you have done is creating an administrator in the administrator database, which is great. However, you are trying to connect to "mydb" directly with an administrator user who is not allowed. Sound confusing? This is because it is. To illustrate this better, this is a simple exercise:

  • Create a user for admin db, as you are already above.
  • get out of mongo shell
  • follow these steps
 mongo use myDBname db.auth("adminlogin", "adminpwd") 

It will not succeed. But try this instead.

 mongo use admin db.auth("adminlogin", "adminpwd") use myDBname 

This will work because you switched to this db using the admin context and did not try to connect directly to it.

So, all you need to do to make this work directly related to the desired DB and create a user right in this db, as shown below:

 mongo use myDBname db.addUser("dblogin", "dbpwd") 

Update the grails configuration file with this, and I bet it will work.

Please note that only the last part is your answer and solves your problem, but since I struggled with this and realized how difficult it is, I think the context really helps to better understand the mango out.

Care

+13
source share

All Articles