Issue with mongodb user authentication - mongodb

I am trying to connect from SERVER-1 to my mongo server which is running in some other sever SERVER-2
So my grails app is running in SERVER-1. So I have given external configuration like this.
grails {
mongo {
host = "<SERVER-2>-host"
port = 27017
username = "myapp"
password = "myapp"
databaseName = "myapp"
options {
autoConnectRetry = true
connectTimeout = 3000
}
}
}
And in the SERVER-2 I've created myapp db and with the same user and credentials
use myapp
db.createUser( { "user" : "myapp",
"pwd": "myapp",
"roles" : [] },
{ w: "majority" , wtimeout: 5000 } )
And am able to see the users list like below
> db.getUsers()
[
{
"_id" : "myapp.myapp",
"user" : "myapp",
"db" : "myapp",
"roles" : [ ]
}
]
Mongo configuration contains "noauth=true",
And from SERVER-1, I'm able to connect to SERVER-2 mongo using the below command
mongo SERVER-2-HOST:27017/myapp -u myapp -p myapp
But when i try to connect from SERVER-1 grails application, its giving the below error
| Error Error executing script LoadVars: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'mongoTransactionManager' while setting constructor argument with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTransactionManager': Cannot resolve reference to bean 'mongoDatastore' while setting bean property 'datastore'; nested exception is org.springframework.beans.factory.BeanCreationException: 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 [myapp], username = [myapp], password = [m***p]
My mongod.conf file
# mongod.conf
logpath=/var/log/mongodb/mongod.log
logappend=true
fork=true
#port=27017
dbpath=/var/lib/mongo
pidfilepath=/var/run/mongodb/mongod.pid
# Listen to local interface only. Comment out to listen on all interfaces.
#bind_ip=127.0.0.1
# nojournal=true
#cpu=true
#noauth=false
auth=true
Am I missing anything here?

Looks like your MongoDB server is running and listening properly but not able to authenticate.
The first problem I'm seeing is that, you mentioned your Grails application is running on 1st server while your MongoDB server is on the 2nd, but the host in your DataSource.groovy configuration is configured to connect to the 1st host, not the 2nd. Is that just in the example or your code is really connecting to the 1st server (which is wrong)? Please verify it.
The second problem might be with the way you are adding the user to the database name myapp. Please follow these steps and try again after connecting:
1) Login to MongoDB instance on the 2nd host: mongo
2) Use your database use myapp
3) Verify that you don not have any user named myapp by running db.dropUser("myapp")
4) Now add the user:
db.createUser({
user: "myapp",
pwd: "myapp",
roles: [ "readWrite", "dbAdmin" ]
});
Now connect your Grails application.
Update
If you are using MongoDB 3.x and Grails 2.5.x or 2.4.x then this should be the problem of your authentication failure. I almost forgot to tell you this problem.
Grails somehow shipping the older version of Java driver i.e. 2.12.3 and to support MongoDB 3, we require minimum 2.13.x of Java driver. Also, the 3.0 Java driver is not a required upgrade for MongoDB 3.0. The 2.13.0 release is the minimum required for full compatibility with MongoDB 3.0.
https://github.com/mongodb/mongo-java-driver/releases/tag/r3.0.0
So, in your BuildConfig.groovy add this as dependency:
dependencies {
compile "org.mongodb:mongo-java-driver:2.13.1"
}
Also, if you are using Grails mongeez plugin, exclude the java driver from there:
compile (":mongeez:0.2.3") {
excludes("mongo-java-driver")
}
I'll create a ticket for this in Grails. Hope this helps!

Creating database-specific authentic user:
1. Run mongod from cmd
2. Run mongo from cmd
3. use "your_db_name"
4.
db.createUser(
{
user: "anik",
pwd: "password",
roles: [ { role: "dbOwner", db: "your_db_name" } ]
}
)
Take note of the db name. Insert urs.
5. mongo "your_db_name" -u anik -p password
6. Switch to your collections bson folder
7. mongorestore -d ss "abc.bson"
After Authentication you can connect to db using username password from your project properties file.

I got the issue with my setup.
Actually I was using grails mongo version 3.0.0
and I installed MongoDB 3.0.0. So according to this grails mongo documentation, grails mongo 3.0.0 plugin supports only MongoDB 2.6. But I was using 3.0.0(upgraded version).
Check this.
https://github.com/grails/grails-data-mapping/issues/557
So now MongoDB 3.0 doesn't support SCRAM-SHA-1 authSchema. So we should use some other techniques to authenticate our user.

Related

IntelliJ Database explorer won't work with localhost Mongo 4.4.3

I'm up-the-middle MongoDB with authentication localhost. I have the mongod configured to bind a specific user to a specific database and from the mongo shell and my Java programs, everything works great. When I log in as that user I can do all the mongo stuff on the mongo db I bound that user to.
$ mongo -u totallyLegitUser --authenticationDatabase admin
MongoDB shell version v4.4.3
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("2ba7a3f6-2ca1-49b7-8241-8133ceb3d842") }
MongoDB server version: 4.4.3
> use mfg-plan;
switched to db mfg-plan
> show collections;
activity
...
When I try to set up the same user through IntelliJ's "Database" thing, the "Test Connection" says everything is fine, but I can't run any queries through the console and the "explorer" drop down thing doesn't show collections I know are in the database.
This is what shows up when I look in the console after I've try to run the db.activity.findOne(); from the cli session...
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-256, userName='totallyLegitUser', source='mfg-plan', password=<hidden>, mechanismProperties=<hidden>} com.mongodb.MongoCommandException: Command failed with error 17 (ProtocolError): 'Attempt to switch database target during SASL authentication.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Attempt to switch database target during SASL authentication.", "code": 17, "codeName": "ProtocolError"}
I have confirmed that the username, password, and database are all correct.
How do I get IntelliJ to connect to my authenticating mongos?
Problem solved. In the "Data Sources and Drivers" dialog for my mongo hosts it asks for a Database. I was giving it the database I wanted to connect to on the host (mfg-plan). What it wants is the authenticationDatabase for the host (usually 'admin'). When I change that to 'admin', all is well.

Getting this error when connecting mongodb in docker-compose with spring-boot application

"ctx":"conn18","msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-1","speculative":false,"principalName":"user","authenticationDatabase":"user_db","remote":"172.20.0.8:51928","extraInfo":{},"error":"UserNotFound: Could not find user "user" for db "user_db""}}
where user is my username & user_db is the database name
Add the authSource=admin at the end of the uri in spring-boot application.yml file
spring:
data:
mongodb:
uri: mongodb://user:pass#localhost:27017/user_db?authSource=admin

Remote MongoDB access through Cloud 9 gives login failed exception

I'm using the Cloud 9 IDE to develop an application using MongoDB. I created a database called "appdata" at MongoLab and the following user:
{
"_id": "appdata.admin",
"user": "admin",
"db": "appdata",
"credentials": {
"SCRAM-SHA-1": {
"iterationCount": 10000,
"salt": "K/WUzUDbi3Ip4Vy59gNV7g==",
"storedKey": "9ow35+PtcOOhfuhY7Dtk7KnfYsM=",
"serverKey": "YfsOlFx1uvmP+VaBundvmVGW+3k="
}
},
"roles": [
{
"role": "dbOwner",
"db": "appdata"
}
]
}
Whenever I try connecting to the database through Cloud 9 Shell using the following command (given by MongoLab with my newly created user):
mongo ds057244.mongolab.com:57244/appdata -u admin -p admin
I get the following error message:
MongoDB shell version: 2.6.11
connecting to: ds057244.mongolab.com:57244/appdata
2015-11-22T05:23:49.015+0000 Error: 18 { ok: 0.0, errmsg: "auth failed",
code: 18 } at src/mongo/shell/db.js:1292
exception: login failed
Also, on my javascript file running on Cloud 9, while following this tutorial (which uses mongoose to access the DB) I got stuck on the post route for bears. Whenever I send a post request through postman with the specified fields set, the route doesn't return anything, neither a bear created nor an error message, which makes me think the problem is also failing to login to the database. The previous get request is working just fine and my code is the exactly same as the tutorial.
Does anyone know what the problem in any of the cases and what I need to do to solve them?
The shell problem was fixed updating it to the Database version (which was 3.0.3).
For the javascript files, I restarted the tutorial and made sure I downloaded all necessary dependencies with the most recent stable version (not the ones shown on the tutorial), after that the problem was solved.

Meteor and MongoDB: Authentication failures

If I run Meteor locally it works perfectly. If I call Meteor with a MONGO_URL that has no username:password it works perfectly too. However, if I turn on the MongoDB authentication and restart and then run Meteor with the username:password set, as in MONGO_URL="mongodb://username:password#127.0.0.1:27017/meteor", then I get an authentication failure as Meteor loads. I have checked that the username and password are correct. I have read that there maybe problems with Meteor and MongoDB authentication so does anyone have any information on this? I am using the following versions:
Meteor - 1.0.3.2
MongoDB - 2.6.7 (installed via brew)
I20150304-21:48:00.597(1)? Exception in callback of async function: MongoError: auth failed
I20150304-21:48:00.598(1)? at Object.toError (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/utils.js:110:11)
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/db.js:1128:31
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/db.js:1843:9
I20150304-21:48:00.598(1)? at Server.Base._callHandler (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/server.js:468:18
I20150304-21:48:00.598(1)? at [object Object].MongoReply.parseBody (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
I20150304-21:48:00.599(1)? at [object Object].<anonymous> (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/server.js:426:20)
I20150304-21:48:00.599(1)? at [object Object].emit (events.js:95:17)
I20150304-21:48:00.599(1)? at [object Object].<anonymous> (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:201:13)
I20150304-21:48:00.599(1)? at [object Object].emit (events.js:98:17)
=================================================
I thought I had an answer to the above but alas not, I made suggested changes and I still could not authenticate. So, to provide more details:
I have upgraded to MonogoDB 3.0.0
I delete the database so that a brand new one was created.
My config file is as follows:
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
storage:
dbPath: /usr/local/var/mongodb
net:
bindIp: 127.0.0.1
security:
authorization: enabled
On the "admin" database a "super user" has been created as follows:
use admin
db.createUser({user: "superuser", pwd: "password", roles:["root"]})use admin
I then created a user on the "meteor" database
db.auth("superuser", "password")
use meteor
db.createUser({user: "meteor", pwd: "password", roles: [{ role: "readWrite", db: "meteor"}]})
The above step generates:
Successfully added user: {
"user" : "meteor",
"roles" : [
{
"role" : "readWrite",
"db" : "meteor"
}
]
}
If I perform a db.getUsers() I get the message:
[
{
"_id" : "meteor.meteor",
"user" : "meteor",
"db" : "meteor",
"roles" : [
{
"role" : "readWrite",
"db" : "meteor"
}
]
}
]
If I comment out the two security lines in the config then I can access MongoDB from Meteor or RoboMongo without a problem - using mongodb:127.0.0.1:27017/meteor. If I uncomment the two security lines in the config then I can no longer access MongoDB from either Meteor or MongoDB - using mongodb://meteor:password#127.0.0.1:27017/meteor. In the last instance I continue to get the message that authentication failed. In the MongoDB logs I have:
authenticate db: meteor { authenticate: 1, nonce: "xxx", user: "meteor", key: "xxx" }
2015-03-08T14:34:44.909+0100 I ACCESS [conn7] Failed to authenticate meteor#meteor with mechanism MONGODB-CR: AuthenticationFailed UserNotFound Could not find user meteor#meteor
Update
The answer below and the configuration above work on v2.6.7
I haven't seen the issues you describe and without seeing code or knowing how you "turned on" MongoDB authentication I need to guess - so let's focus on what made things work for me.
You should check where the user was created. In MongoDB there are multiple databases, each having their own users. When using your connection string
mongodb://username:password#127.0.0.1:27017/meteor
you are authenticating against the meteor database. Using a tool such as RoboMongo I'd check if the user is actually inside that database or whether you created it inside the admin (or any other) database.
As a quick rundown:
When securing MongoDB you need to set an admin account, change the mongodb.conf file that it contains the line auth = true and restart. Then using the admin account you create a new (low-privilege) db user that has only access to the meteor database. You can do this using the command line like this (code for 2.6 as this was in your questions and will be default for next Meteor version):
db.createUser(
{ user: "username",
pwd: "password",
roles: [
{ role: "readwrite", db: "meteor" }
]
})
If you run mongod on the same box as Meteor I think we can safely rule out any issues with net.port or net.bindIpconfig settings where the DB would simply not listen to requests.
If you did all this and restarted MongoDB, perhaps a meteor reset inside your projects can help fix anything.
it turns out for me was just about having special chars on the password and a dash on the username, once i made it simpler it all worked like magic :(
I had the same issue when I deployed on my new VPS.
On this new VPS, mongo version is 3.0.1
To solve the problem, a meteor update before building the package and it works
(meteor version: 1.0.4.1)

Sailsjs v0.10 sails-mongo not creating database and collections on sails lift

I'm using npm to install:
sailsjs: npm install -g git://github.com/balderdashy/sails.git (v0.10 - master)
sails-mongo adapter: npm install git://github.com/balderdashy/sails-mongo.git (also v0.10 - master)
mongoDB version : 2.6.1
When executing "sails lift", I'm expecting it to
a) lift my server
b) create my database on mongodb server and the collections defined in my models.
config :
connections.js
mongo : {
adapter: 'sails-mongo',
host: '127.0.0.1',
port: 27017,
user: '',
password : '',
database : 'mydb'
}
models.js
connection : 'mongo'
I have not defined any additional connection information in local.js
I lift my server, check mongodb via the terminal and do not see "mydb" created.
Any idea's?
extra info
I did read that if you have any configuration issues when defining an adapter that it will default to the localDiskDb.