Can't authenticate with mongoenine to mongodb replicas - mongodb

1) Before even setting replica sets in mongo i created admin user, with "readWriteAnyDatabase", "userAdminAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin" roles.
2) Then i set my /etc/mongodb.conf configurations on all 3 servers.
dbpath=/var/lib/mongodb
logpath=/var/log/mongodb/mongodb.log
logappend=true
port = 27017
auth = true
replSet = test4
3) Initiated replicas, but got error
(Do not remember exactly what the error was, but something related to that one of the server was not up. So i figured that it just can't authenticate)
config = {"_id" : "test4", "version" : 1, "members" : [{"_id" : 0,"host" : "xxx.xxx.xxx.xxx:27017"}, {"_id" : 1,"host" : "xxx.xxx.xxx.xxx:27017"}, {"_id":2,"host" : "xxx.xxx.xxx.xxx:27017"}]}
rs.initiate(config)
4) To solve the error, i generated keyFile and added keyFile authentication to my mongodb.conf file.
dbpath=/var/lib/mongodb
keyFile = /etc/keyFile
logpath=/var/log/mongodb/mongodb.log
logappend=true
port = 27017
auth = true
replSet = test4
And everything worked like a charm. Database copied itself over replicas. Admin user worked as expected too.
5) Then i created user with all needed permissions for other database i have, lets call it 'testdb' and user: notadmin, pass: notadmin.
But there is one strange thing i noticed. When i enter mongo in console i do not see replicas, until i log in admin database as an admin like this:
use admin
db.auth('admin', 'admin')
Then my console changes to test4:PRIMARY> or test4:SECONDARY> and i can perform actions with replicas. Guess it should be like this.
And everything works fine, if i insert data through pymongo library. Permissions work, admin user can insert into any database, given permissions, and notadmin user can insert into testdb.
But if i try to make the same thing with mongoengine models,
mongodsn = 'mongodb://notadmin:notadmin#xxx.xxx.xxx.xxx:27017,xx.x.xx.xxx:27017,xxx.xxx.xxx.xx:27017/'
db_instance = mongoengine.connect('testdb', host=mongodsn, replicaSet='test4', readPreference='secondaryPreferred')
rt = ReconnectTest()
rt.content = 'item#{0:d}'.format(x)
rt.save()
i get authentication error:
mongoengine.errors.OperationError: Could not save document (command
SON([('authenticate', 1), ('user', u'notadmin'), ('nonce',
u'9ae2f85cd41f6c74'), ('key', u'8f814aa2434s4t2e0ff9bae03762e')])
failed: auth fails)
The only thing it permits me is from admin user to write to admin database. So something like this works:
mongodsn = 'mongodb://admin:admin#xxx.xxx.xxx.xxx:27017,xx.x.xx.xxx:27017,xxx.xxx.xxx.xx:27017/'
db_instance = mongoengine.connect('admin', host=mongodsn, replicaSet='test4', readPreference='secondaryPreferred')
rt = ReconnectTest()
rt.content = 'item#{0:d}'.format(x)
rt.save()
I am so confused, because mongoengine is just wrapper around pymongo. So how come i can do actions with pymongo, and can't do the same with mongoenige. How do i authenticate with mongoengine to testdb ?

You need to create a user under the "testdb" database, as follows:
$ mongo admin -u <username> -p <password>
> use testdb
> db.addUser({user: <username>, pwd: <password>, roles: [<permissions>]})
Then trying to connect through mongoengine using the newly created user.
Also, add the database in the connection string, as such:
'mongodb://notadmin:notadmin#xxx.xxx.xxx.xxx:27017/testdb'

Related

mongo : not authorizeed on admin to execute on admin to execute command

I am new to Mongod, and have to get up a cluster. The db is started with --replSet=Data and I have created the cluster with rs.Initiate beforehand. But this question is about user administration.
This replica set was set up with this command:
rs.initiate({ _id : "Data",members: [
{ _id: 0, host: "srv1:27017" },
{ _id: 1, host: "srv2:27017" },
{ _id: 2, host: "srv3:27017" , arbiterOnly: true }
})
And the server was started with $ /usr/bin/mongod -f /etc/mongod.conf --replSet=rs0
Note that I have not yet configured the other nodes/added these into the cluster as far as I am aware, but I did distribute the keyFile: /etc/mongod/keyfile to each server.
An rs.status says it's not running.
> rs.Status();
{
"ok : 0"
"errmsg" : no replset config has been received",
"code" : 94,
"codename" : "NotYetInitialized"
}
I have run into some nib problems.
I created a user before called mgdb with the command :
# mongo admin -port 27017
> db.createUser ( {
user : 'mgdb', pwd: 'password', roles: [ { roles: root, db: admin } ]
})
This returned ok.
Next I tried with,
$ mongo --authenticationDatabase admin --username "mgdb" --password "password"
but got an error
E QUERY [js] Error authentication failed.
Next I tried to see the user list,
> show users;
not authorizeed on admin to execute on admin to execute command { UserInfo: 1.0}, lsid: { id: UID"xxxxxxxx") }. $db: "admin" } DB.prototy[e.getUsers#.....
So, I am bit lost. I used mysql a few years ago, but have not used it since. My dB experience is very little.
Although I can connect as the admin user, the admin user does not seem to have rights to do basic "show users;"
Where can I look in the dB to find out what went wrong?
Environment: RHEL 7.6 SELinux Enforcing, MOngdodB 4.2.9
In MongoDB you can create users per database. Usually users are create in database admin (I wouldn't know any reason to create them somewhere else):
use admin
db.createUser(...
or
db.getSiblingDB("admin").createUser(...
When you connect to Mongo then you need to specify the authentication database, i.e. the database where user was created:
mongo --usermame=mgdb --password 'password' --authenticationDatabase admin
See Authentication failure while trying to save to mongodb
In order to deploy a sharded cluster have a look at Deploy a Sharded Cluster or Deploy a Replica Set tutorial.

Mongo DB 3.2 Authentication

I've just followed this guide on setting up Auth with Mongo DB, as well as this guide to get a user set up as an administrator.
Running mongo > use admin > show users prints the following:
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
After this, I run the server again with --auth and use the following command:
mongo -u "root" -p "xxx" --authenticationDatabase "admin"
This prints the following:
MongoDB shell version: 3.2.19
connecting to: test
2018-03-29T15:52:32.329+0200 E QUERY [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow#src/mongo/shell/db.js:1441:20
#(auth):6:1
#(auth):1:2
exception: login failed
Trying to run this without the --auth parameter lets me log in just fine.
The --auth parameter also gives me the following output in the server console:
I ACCESS [conn1] note: no users configured in admin.system.users, allowing localhost access
But I'm actually unsure about why it isn't picking up any root/admin user I create. When trying to connect with Robo 3T, the terminal prints the following:
I NETWORK [initandlisten] connection accepted from xxx:44924 #2 (2 connections now open)
I ACCESS [conn2] SCRAM-SHA-1 authentication failed for root on admin from client xxx ; UserNotFound: Could not find user root#admin
I NETWORK [conn2] end connection xxx:44924 (1 connection now open
Solution by OP.
Issue fixed by following this article.
It seems that, despite using --auth when connecting to the server, by not commenting out the line bindIp: 127.0.0.1 and adding authorization: 'enabled' to the security section in /etc/mongod.conf, I was only allowing access to the local machine - the server itself. The error messages could have been worded a bit better, but that's security. I guess.
Whilst this was a very silly oversight, no documentation I had previously looked at had covered this issue.

mongodb authentication disable and enable issue

Now I have a mongoDB in my computer,locates at c:\mongodb\bin. At first, it is auth disable. so when I press:
C:\Windows\system32>mongo
There is some warnings:
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] ** WARNING:
Access contr ol is not enabled for the database.
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] **
Read and wri te access to data and configuration is unrestricted.
So I tried to add access control to mongoDB. What I did are:
C:\mongodb\bin>use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
But after I did above, still I can log in MongoDb without username and pwd. Even after I restart the mongoDB service, or restart the computer. eg:
C:\Windows\system32>mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings:
2018-03-28T16:53:43.515+0800 I CONTROL [initandlisten]
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] ** WARNING: Access contr
ol is not enabled for the database.
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] ** Read and wri
te access to data and configuration is unrestricted.
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten]
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] Hotfix KB2731284 or late
r update is not installed, will zero-out data files.
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten]
> show dbs
admin 0.000GB
local 0.000GB
> use admin
switched to db admin
>
The only way that I can make the mongodb change to authentication is delete the mongodb service and install this service again by using follwoing script:
C:\mongodb\bin>sc delete MongoDB
C:\mongodb\bin>mongod --dbpath C:\mongodb\data --logpath C:\mongodb\log\MongoDB.log --auth --install
But If I use this way to create the auth mongoDB, when I try to login without username and pwd, it will faied as below:
C:\Windows\system32>mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
> show dns
2018-03-28T17:59:06.344+0800 E QUERY [thread1] Error: don't know how to show
[dns] :
shellHelper.show#src/mongo/shell/utils.js:906:11
shellHelper#src/mongo/shell/utils.js:659:15
#(shellhelp2):1:1
> show dbs
2018-03-28T17:59:10.073+0800 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases:
1.0 }",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode#src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs#src/mongo/shell/mongo.js:62:1
shellHelper.show#src/mongo/shell/utils.js:769:19
shellHelper#src/mongo/shell/utils.js:659:15
#(shellhelp2):1:1
>
So I can NOT create a user and pwd for this mongoDB. How could I login?
Anybody can tell me how to do the setting step by step to make my mongoDB to authentication? or delete a old mongoDB and create a new one with authutication and also with username and pwd?
I will get an exception below if I tried to set a without auth mongoDB and auth one.
C:\Windows\system32>mongod --auth --port 27017 --dbpath C:\mongodb\data
2018-03-28T16:49:43.874+0800 I CONTROL [initandlisten] MongoDB starting : pid=7
988 port=27017 dbpath=C:\mongodb\data 64-bit host=wolf-PC
.....
2018-03-28T16:49:43.877+0800 I STORAGE [initandlisten] exception in initAndList
en: 98 Unable to create/open lock file: C:\mongodb\data\mongod.lock Another program is using this file.... Is a mongod instance already running?, terminating
I checked the questions:
MongoDB: Server has startup warnings ''Access control is not enabled for the database''
which I failed to follow with step4 on above excpetion.
MongoDB: Server has startup warnings
I got the same exception.
So anyone can give me a detail soultion?
The reason why authentication is not working in your first example is because you have not yet enabled it. Auth is enabled by configuration only and not by the presence of db users. As you already demonstrated, the way to enable auth is to either start the db with the --auth flag or ensure that authorization is enabled within the security section of your mongod.conf file (like below).
security:
authorization: enabled
Once authorization is enabled, you must authenticate first before performing any operations by using the below options when you start the shell.
mongo <db> -u <username> -p <password>
For example, since you already created your myUserAdmin user on the admin database, then you can authenticate like this:
mongo admin -u myUserAdmin -p abc123
Or, if you have already started the shell with just mongo, then you can authenticate like this:
1) First switch to the admin db.
use admin
2) Then authenticate your user:
db.auth('myUserAdmin ', 'abc123')
Also, keep in mind that the userAdminAnyDatabase is a very powerful admin role, but it only allows read/write access to the admin database (not databases that you create to store data for your app). It also enables admin operations (e.g. createUser, createRole, etc) across ALL databases which could be dangerous if compromised.
So, if you are trying to create a user to read/write from a non-system database, then you should create a different, specific user for that. For Example...
1) authenticate your admin user (like what was shown above).
2) create a new user to read/write from your app database:
db.createUser(
{
user: <app db user>,
pwd: <password>,
roles: [ { role: "readWrite", db: <app db> } ]
}
);
Here is more detail about each of the mongodb roles and how they behave.

MongoDB 3.2 - creating a CRUD admin for a certain database

I'm trying to create a CRUD database administrator.
From what I read from official documentation, there is a role readWrite, but I don't really got the process of creating an admin.
So I ran mongod without --auth and created a user with these parameters:
use myCustomDB
db.createUser({
user: "snoop",
pwd:"stickyickyicky",
roles:[{role:"readWrite", db:"myCustomDB"}]
});
The command line answered Successfully added new user blah blah..
but when I authenticate it returns 1, which, I suppose is true. But when I run command for example db.peops.find() it gives me this Error: error: { "$err" : "not authorized for query on myCustomDB.peops", "co de" : 13 }
It may be your find call. Try formatting like this:
db.getCollection('peops').find({})
If that's not it, it might be your auth schema. This may not be the best method, but I thought I would share the steps I take to setup a super admin and database specific admin, and a read only user. The all caps should be replaced with corresponding credential / db name:
1.Change Mongo Security Method
sudo service mongod start
mongo
use admin
db.system.version.remove({})
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
2.Create Super Admin User
use admin
db.createUser( { user: "SUPERADMINUSER", pwd: "SUPERADMINPASS", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
3.Create db Admin with read/write access
use DATABASE
db.createUser( { user: "DBADMIN", pwd: "DBPASSWORD", roles: [ { role: "userAdmin", db: "DATABASE" }, { role: "readWrite", db: "DATABASE" }] } )
db.createUser( { user: "DBREADONLYUSER", pwd: "DBREADONLYPASS", roles: [ { role: "read", db: "DATABASE" }] } )
4.Edit mongod.config in /etc folder
sudo service mongod stop
in mongod.config edit so that auth = true is not commented out.
5. Restart mongo, security in place
sudo service mongod start
***Troubleshooting: If you are running mongo 3.2 you can likely skip the db.system.version remove and insert commands, you may want/need to upgrade to SCRAM-SHA-1, if so run db.adminCommand({authSchemaUpgrade: 1}); set up users the same way as shown above, when editing your /etc/mongod.conf file instead of auth=true comment in security: and add authorization=true as follows:
security:
authorization: enabled

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)