MongoDB - admin user not authorized - mongodb

I am trying to add authorization to my MongoDB.
I am doing all this on Linux with MongoDB 2.6.1.
My mongod.conf file is in the old compatibility format
(this is how it came with the installation).
1) I created admin user as described here in (3)
http://docs.mongodb.org/manual/tutorial/add-user-administrator/
2) I then edited mongod.conf by uncommenting this line
auth = true
3) Finally I rebooted the mongod service and I tried to login with:
/usr/bin/mongo localhost:27017/admin -u sa -p pwd
4) I can connect but it says this upon connect.
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:47:16 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
5) Now it seems this sa user I created has no permissions at all.
root#test02:~# mc
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:57:03 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
[admin] 2014-05-29 17:57:03.011 >>> use admin
switched to db admin
[admin] 2014-05-29 17:57:07.889 >>> show collections
2014-05-29T17:57:10.377-0400 error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
[admin] 2014-05-29 17:57:10.378 >>> use test
switched to db test
[test] 2014-05-29 17:57:13.466 >>> show collections
2014-05-29T17:57:15.930-0400 error: {
"$err" : "not authorized for query on test.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
[test] 2014-05-29 17:57:15.931 >>>
What is the problem? I repeated this whole procedure 3 times and
I think I did it all as specified in the MongoDB docs. But it doesn't work.
I was expecting this sa user to be authorized to do anything so that
he can then create other users and give them more specific permissions.

I was also scratching my head around the same issue, and everything worked after I set the role to be root when adding the first admin user.
use admin
db.createUser(
{
user: 'admin',
pwd: 'password',
roles: [ { role: 'root', db: 'admin' } ]
}
);
exit;
If you have already created the admin user, you can change the role like this:
use admin;
db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])
For a complete authentication setting reference, see the steps I've compiled after hours of research over the internet.

It's a bit confusing - I believe you will need to grant yourself readWrite to query a database. A user with dbadmin or useradmin can admin the database (including granting yourself additional rights) but cannot perform queries or write data.
so grant yourself readWrite and you should be fine -
http://docs.mongodb.org/manual/reference/built-in-roles/#readWrite

Perhaps a quick example of how to change a current user will be helpful to somebody. This is what I was actually looking for.
Following advice of #JohnPetrone I added readWrite role to my admin user with grantRolesToUser
> use admin
> db.grantRolesToUser("admin",["readWrite"])
> show collections
system.users
system.version

You can try: Using the --authenticationDatabase flag helps.
mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"

I know this answer is coming really late on in this thread but I hope you check it out.
The reason you get that error is based on the specific role that you granted to the user, which you have gathered by now, and yes giving that user the role root will solve your problem but you must first understand what these roles do exactly before granting them to users.
In tutorial you granted the user the userAdminAnyDatabase role which basically give the user the ability to manage users of all your databases.
What you were trying to do with your user was outside its role definition.
The root role has this role included in it definition as well as the readWriteAnyDatabase, dbAdminAnyDatabase and other roles making it a superuser (basically because you can do anything with it).
You can check out the role definitions to see which roles you will need to give you users to complete certain tasks.
https://docs.mongodb.com/manual/reference/built-in-roles/
Its not advisable to make all your users super ones :)

It's a simple question.
It's important that you must switch the target db NOT admin.
use yourDB
check your db authentication by
show users
If you get a {} empty object that is the question. You just need to type
db.createUser(
{
user: "yourUser",
pwd: "password",
roles: [ "readWrite", "dbAdmin" ]
} )
or
db.grantRolesToUser('yourUser',[{ role: "dbAdmin", db: "yourDB" }])

If you're using Atlas, note that you can't create users through the mongo shell.
I was banging my head against the wall for a while till I came across this:
https://www.mongodb.com/community/forums/t/cant-create-a-root-user-from-mongo-shell/101369

I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :)
Try this:
Choose your project in the MongoDB atlas website
Connect/Connect with MongoDB Compass
Download Compass/Choose your OS
I used Compass 1.12 or later
Copy the connection string under the Compass 1.12 or later.
Open MongoDB Compass/Connect(top left)/Connect To
Connection String detected/Yes/
Append your project name after the hostname: cluster9-foodie.mongodb.net/projectname
Connect & Tested the API with POSTMAN.
Succeed.
Use the same connection string in your code too:
Before:
mongodb+srv://projectname:password#cluster9-foodie.mongodb.net/admin
After:
mongodb+srv://projectname:password#cluster9-foodie.mongodb.net/projectname
Good luck.

Use Admin :
use admin
Create a super user :
db.createUser(
{
user: "master",
pwd: "test#123",
roles: [
{
role: "readWriteAnyDatabase",
db: "admin"
},
{
"role" : "dbAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "clusterAdmin",
"db" : "admin"
},
"userAdminAnyDatabase"
]
}
)

I came across this thread with a similar issue, but my problem was that I used the collection name instead of the database name.

I had a similar problem here on a Windows environment: I have installed Bitnami DreamFactory and it also installs another MongoDb that is started on system boot. I was running my MongoDbService (that was started without any error) but I noticed after losing a lot of time that I was in fact connecting on Bitnami's MongoDb Service. Please, take a look if there is not another instance of mongoDB running on your server.
Good Luck!

In addition, notice that if your mongo shell client fails to connect correctly to the mongod instance, you can receive such "Permission Denied" errors.
Make sure that your client opens a connection by checking the connection port, but also that the port you are using in mongod is not in use. You can set a different port by using the --port <port> parameter in both the shell and the process.

use mydb
db.createUser( { user: "test", pwd: "secret", roles: [ "readWrite", "dbAdmin"],passwordDigestor:"server" } )

Agreed that you've to get authenticated to admin db and needs at least a role with correct privileges which would avoid 'local host exception' from DB(this is for mongoDB's hosted on-premises), though you've everything in place & still getting not authorized exceptions on almost every command, while accessing mongoDB which got created using Mongo Atlas, then here is the place where you might know the reason, why :
https://dba.stackexchange.com/questions/219003/not-authorized-on-admin-to-execute-command-mongodb-atlas-m0-free-tier-cluster?newreg=471a9a26108243d78d4ca74a87e7a115
and also check this if you've hosted mongoDB on mongo Atlas:
https://docs.atlas.mongodb.com/unsupported-commands/

I followed these steps on Centos 7 for MongoDB 4.2. (Remote user)
Update mongod.conf file
vi /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
security:
authorization: enabled
Start MongoDB service demon
systemctl start mongod
Open MongoDB shell
mongo
Execute this command on the shell
use admin
db.createUser(
{
user: 'admin',
pwd: 'YouPassforUser',
roles: [ { role: 'root', db: 'admin' } ]
}
);
Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T

For MongoDB shell version v4.2.8 I've tried different ways to back-up my database with auth, my winner solution is
mongodump -h <your_hostname> -d <your_db_name> -u <your_db_username> -p <your_db_password> --authenticationDatabase admin -o /path/to/where/i/want

This may be because you havent set noAuth=true in mongodb.conf
# Turn on/off security. Off is currently the default
noauth = true
#auth = true
After setting this restart the service using
service mongod restart

Related

db.serverStatus() returns "not authorized to execute command" on mlab w/ owner privileges

I recently opened up a free mLab account, and I'm trying to access the number of open connections in my database through the shell.
I never had problems with the command line when I was running mongodb locally, but now nothing works.
To connect I do this:
mongo ds127044.mlab.com:27044/db_name -u db_user -p db_password
And it show I'm successfully connected.
After that I run:
db.serverStatus()
And get:
{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { serverStatus: 1.0 }",
"code" : 13,
"codeName" : "Unauthorized"
}
But according to my console I'm listed as the owner of the db:
{
"_id": "db_name.db_user",
"user": "db_user",
"db": "db_name",
"roles": [
{
"role": "dbOwner",
"db": "db_name"
}
]
}
Is there something I'm doing wrong in the command line or is it something particular to my account with mLab?
Seems to be something related with your user's roles.
All documentation here: https://docs.mongodb.com/manual/reference/built-in-roles/#cluster-admin-roles/ (specifically cluesterMonitor information)
Say:
...The admin database includes the following roles for administering the
whole system rather than just a single database...
And in this Doc https://docs.mongodb.com/manual/core/security-built-in-roles/
Say:
Every database includes: Database Administration Roles... The
admin database includes the following roles for administering the
whole system: Cluster Administration Roles
'serverStatus' is realted to clusterMonitor role so..
Try to change it:
roles: [ { role: "clusterMonitor", db: "admin" },
{ role: "dbOwner", db: "db_name" }]
Good luck!
Not a mongodb expert, but here's what I found in the docs.
db.serverStatus() shares instance info in its output. For example:
host
The system’s hostname. In Unix/Linux systems, this should be the same as the output of the hostname command.
mLab wouldn't expose host info to end users, who should only have access to the dbs they're creating--specifically, the db you logged into.
Similarly, you'll run into issues with other calls like show dbs, since that would expose all the dbs (including dbs for other users!) existing alongside your own.
I imagine that the only commands that will work are ones that expose info completely related to only your db. I suggest hitting up a more export mongodb admin perhaps in a separate question for that definitive list, if necessary.
I fixed this exact issue by changing my mac settings to allow remote login.
System Preferences -> Sharing -> Remote Login: On

not able to run "show dbs" on mongodb on Bitnami image instance from aws ec2 instance [duplicate]

I am trying to add authorization to my MongoDB.
I am doing all this on Linux with MongoDB 2.6.1.
My mongod.conf file is in the old compatibility format
(this is how it came with the installation).
1) I created admin user as described here in (3)
http://docs.mongodb.org/manual/tutorial/add-user-administrator/
2) I then edited mongod.conf by uncommenting this line
auth = true
3) Finally I rebooted the mongod service and I tried to login with:
/usr/bin/mongo localhost:27017/admin -u sa -p pwd
4) I can connect but it says this upon connect.
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:47:16 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
5) Now it seems this sa user I created has no permissions at all.
root#test02:~# mc
MongoDB shell version: 2.6.1
connecting to: localhost:27017/admin
Welcome to the MongoDB shell!
The current date/time is: Thu May 29 2014 17:57:03 GMT-0400 (EDT)
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
[admin] 2014-05-29 17:57:03.011 >>> use admin
switched to db admin
[admin] 2014-05-29 17:57:07.889 >>> show collections
2014-05-29T17:57:10.377-0400 error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
[admin] 2014-05-29 17:57:10.378 >>> use test
switched to db test
[test] 2014-05-29 17:57:13.466 >>> show collections
2014-05-29T17:57:15.930-0400 error: {
"$err" : "not authorized for query on test.system.namespaces",
"code" : 13
} at src/mongo/shell/query.js:131
[test] 2014-05-29 17:57:15.931 >>>
What is the problem? I repeated this whole procedure 3 times and
I think I did it all as specified in the MongoDB docs. But it doesn't work.
I was expecting this sa user to be authorized to do anything so that
he can then create other users and give them more specific permissions.
I was also scratching my head around the same issue, and everything worked after I set the role to be root when adding the first admin user.
use admin
db.createUser(
{
user: 'admin',
pwd: 'password',
roles: [ { role: 'root', db: 'admin' } ]
}
);
exit;
If you have already created the admin user, you can change the role like this:
use admin;
db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])
For a complete authentication setting reference, see the steps I've compiled after hours of research over the internet.
It's a bit confusing - I believe you will need to grant yourself readWrite to query a database. A user with dbadmin or useradmin can admin the database (including granting yourself additional rights) but cannot perform queries or write data.
so grant yourself readWrite and you should be fine -
http://docs.mongodb.org/manual/reference/built-in-roles/#readWrite
Perhaps a quick example of how to change a current user will be helpful to somebody. This is what I was actually looking for.
Following advice of #JohnPetrone I added readWrite role to my admin user with grantRolesToUser
> use admin
> db.grantRolesToUser("admin",["readWrite"])
> show collections
system.users
system.version
You can try: Using the --authenticationDatabase flag helps.
mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"
I know this answer is coming really late on in this thread but I hope you check it out.
The reason you get that error is based on the specific role that you granted to the user, which you have gathered by now, and yes giving that user the role root will solve your problem but you must first understand what these roles do exactly before granting them to users.
In tutorial you granted the user the userAdminAnyDatabase role which basically give the user the ability to manage users of all your databases.
What you were trying to do with your user was outside its role definition.
The root role has this role included in it definition as well as the readWriteAnyDatabase, dbAdminAnyDatabase and other roles making it a superuser (basically because you can do anything with it).
You can check out the role definitions to see which roles you will need to give you users to complete certain tasks.
https://docs.mongodb.com/manual/reference/built-in-roles/
Its not advisable to make all your users super ones :)
It's a simple question.
It's important that you must switch the target db NOT admin.
use yourDB
check your db authentication by
show users
If you get a {} empty object that is the question. You just need to type
db.createUser(
{
user: "yourUser",
pwd: "password",
roles: [ "readWrite", "dbAdmin" ]
} )
or
db.grantRolesToUser('yourUser',[{ role: "dbAdmin", db: "yourDB" }])
I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :)
Try this:
Choose your project in the MongoDB atlas website
Connect/Connect with MongoDB Compass
Download Compass/Choose your OS
I used Compass 1.12 or later
Copy the connection string under the Compass 1.12 or later.
Open MongoDB Compass/Connect(top left)/Connect To
Connection String detected/Yes/
Append your project name after the hostname: cluster9-foodie.mongodb.net/projectname
Connect & Tested the API with POSTMAN.
Succeed.
Use the same connection string in your code too:
Before:
mongodb+srv://projectname:password#cluster9-foodie.mongodb.net/admin
After:
mongodb+srv://projectname:password#cluster9-foodie.mongodb.net/projectname
Good luck.
Use Admin :
use admin
Create a super user :
db.createUser(
{
user: "master",
pwd: "test#123",
roles: [
{
role: "readWriteAnyDatabase",
db: "admin"
},
{
"role" : "dbAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "clusterAdmin",
"db" : "admin"
},
"userAdminAnyDatabase"
]
}
)
If you're using Atlas, note that you can't create users through the mongo shell.
I was banging my head against the wall for a while till I came across this:
https://www.mongodb.com/community/forums/t/cant-create-a-root-user-from-mongo-shell/101369
I came across this thread with a similar issue, but my problem was that I used the collection name instead of the database name.
I had a similar problem here on a Windows environment: I have installed Bitnami DreamFactory and it also installs another MongoDb that is started on system boot. I was running my MongoDbService (that was started without any error) but I noticed after losing a lot of time that I was in fact connecting on Bitnami's MongoDb Service. Please, take a look if there is not another instance of mongoDB running on your server.
Good Luck!
In addition, notice that if your mongo shell client fails to connect correctly to the mongod instance, you can receive such "Permission Denied" errors.
Make sure that your client opens a connection by checking the connection port, but also that the port you are using in mongod is not in use. You can set a different port by using the --port <port> parameter in both the shell and the process.
use mydb
db.createUser( { user: "test", pwd: "secret", roles: [ "readWrite", "dbAdmin"],passwordDigestor:"server" } )
Agreed that you've to get authenticated to admin db and needs at least a role with correct privileges which would avoid 'local host exception' from DB(this is for mongoDB's hosted on-premises), though you've everything in place & still getting not authorized exceptions on almost every command, while accessing mongoDB which got created using Mongo Atlas, then here is the place where you might know the reason, why :
https://dba.stackexchange.com/questions/219003/not-authorized-on-admin-to-execute-command-mongodb-atlas-m0-free-tier-cluster?newreg=471a9a26108243d78d4ca74a87e7a115
and also check this if you've hosted mongoDB on mongo Atlas:
https://docs.atlas.mongodb.com/unsupported-commands/
I followed these steps on Centos 7 for MongoDB 4.2. (Remote user)
Update mongod.conf file
vi /etc/mongod.conf
net:
port: 27017
bindIp: 0.0.0.0
security:
authorization: enabled
Start MongoDB service demon
systemctl start mongod
Open MongoDB shell
mongo
Execute this command on the shell
use admin
db.createUser(
{
user: 'admin',
pwd: 'YouPassforUser',
roles: [ { role: 'root', db: 'admin' } ]
}
);
Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T
For MongoDB shell version v4.2.8 I've tried different ways to back-up my database with auth, my winner solution is
mongodump -h <your_hostname> -d <your_db_name> -u <your_db_username> -p <your_db_password> --authenticationDatabase admin -o /path/to/where/i/want
This may be because you havent set noAuth=true in mongodb.conf
# Turn on/off security. Off is currently the default
noauth = true
#auth = true
After setting this restart the service using
service mongod restart

How to set password Auth in MongoDB as other RDBMS have?

I am installing mongoDB on my Ubuntu 14.04
mongod version : 3.0.4
mongoshell version : 3.0.4
I want to set the password on my database.
I have gone through the mongoDB official Docs and didn't find any good solution for it.
I tried by creating admin db and adding the user into it,it gives me some roles error or sometime it gives me addUses is not the function of admin.
Please suggest me hot to achieve it.
Thanks in advance!
Create a mongoDB configuration file containing:
security:
authorization: enabled
Then start mongoDB with mongod --config ../etc/mongod.conf
Go to your mongo shell and create an admin user with something like this in the shell:
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Afterwards create additional users as needed with the proper roles i.e. read, readWrite.
For more detail look at Enable Authentication. I hope this helps you.

Unable to setup a user adminstrator account in mongodb running on fedora

I have setup mongodb by downloading the 64 bit legacy linux download on the official mongodb website.I started the mongod service, and then installed the mean stack by following the instructions on the meanjs.org website. I started the server and the default boilerplate of meanjs showed up. Now I am trying to setup the user adminstrator for the mongodb server. There was no admin database by default, so I tried the following:
use admin
db.createUser({
user:”siteUserAdmin”,
pwd: “useradminpwd”
roles: [{role: “userAdminAnyDatabase”,db: “admin”}]
})
I am getting the following error:E QUERY SyntaxError: Unexpected token ILLEGAL
There was also a mean-dev database with the following collections:sessions, system.indexes, users so I also tried creating the user adminstrator account in this database and I got the same error.I need guidance to setup the user adminstrator account.
You might want to check mongod.conf and set
auth=true
After that, restart mongod.
Now you need to use the mongo shell on the server mongod is running on.
Your statements look correct, but for completeness:
use admin
db.createUser(
{
user: "siteUserAdmin",
pwd: "yourPassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)

How do I add an admin user to Mongo in 2.6?

I upgraded from 2.4 to 2.6 and authentication broke. This tutorial seems pretty straightforward but I keep getting locked out of my own database. My situation is pretty simple, I have a single Mongo server and need one user/pwd combination to connect.
First I connect via the localhost exception as mentioned. Then I create the admin user as suggested:
use admin
db.createUser(
{
user: "myadmin",
pwd: "mysecret",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
Now it's time to add new users so to sanity check myself, I logout of the shell. Now when I type "mongo" it fails. That used to work but OK, it's not seeing a username password and I guess the localhost exception isn't there anymore so I follow the instructions outlined here:
mongo --port 27017 -u myadmin -p mysecret --authenticationDatabase admin
And I get:
MongoDB shell version: 2.6.0
connecting to: 127.0.0.1:27017/test
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
>
Any idea on how to:
Setup Mongo 2.6 so I can easily go in and out of the shell managing the databases (I would think this is the "system user administrator")
Enable a user from a remote client to connect? (Just the mongo side, no help needed with iptables ...)
Thanks!
Apparently the "system user administrator" isn't enough. Create a root user:
> db.createUser({user:"someadmin",pwd:"secret", roles:[{role:"root",db:"admin"}]})
Then add your database user:
> use some_db
> db.createUser(
{
user: "mongouser",
pwd: "someothersecret",
roles: ["readWrite"]
}
)
More details on this gist. Comments on gist and better answers on SO welcome - I'm not a sys admin
1) The role that you assign the admin user- userAdminAnyDatabase - doesn't have unlimited privileges. It's just a role that is allowed to create and manage users on any database. Apparently, by default it is restricted from executing certain commands that are not directly related to managing database users (such as fetching the startup warnings from the log, querying the server status, etc.).
You can use the 'root' role instead as Tony suggests. If you are going to use the root account to do setup and management and then just have a few basic read/write privileged accounts talking to the database, this probably makes the most sense.
2) In general, connecting on the client side just requires calling the db.authenticate() function after connecting from your client code. There are different ways to do this depending on the driver/language that you are using for a client. The node.js driver code is pretty typical: http://mongodb.github.io/node-mongodb-native/api-generated/db.html#authenticate
Even after following #Tony's method I was getting a
`com.mongodb.CommandFailureException:`
Adding
compile 'org.mongodb:mongo-java-driver:2.13.1'
in Dependency section of BuildConfig.groovy however fixed the issue.