MongoDB - admin user not authorized
Asked Answered
D

17

329

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.

Dine answered 29/5, 2014 at 21:54 Comment(1)
This is very annoying or badly documented. I was struggling myself there. In the end, I have a user with global "root" role ans still cant do some things like execute commands...Polyunsaturated
A
804

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.

Algorism answered 6/4, 2015 at 13:23 Comment(13)
WTF?! lost an hour for a stupid thing like this. Why do they put in documentation userAdminAnyDatabase instead of root?Magnesia
the idea is that you first create a user that is only used for administrating other users (therefore the role starting with "userAdmin") and only then create your normal users. it kind of makes sense, but i didn't get it the first time right too... @MagnesiaSphere
This didn't work for me on MongoDB v3.4.7: db.grantRolesToUser('admin',[{ role: "root", db: "admin" }])Pasquinade
NOTICE Hi there it is not advisable to make all users root the tutorial granted the role userAdminAnyDatabase in order to have a user which had the permission to create other users. If you follow on with the tutorial you will see this user is used to create a user who can now manipulate the database. Check out my answer for a bit more detail. Hopefully it's up-voted and not at the bottom :)Nigrosine
If your admin user doesn't have access to do something, it certainly doesn't have access to give itself root access...Aeronautics
@Aeronautics This code DID work for me: db.grantRolesToUser('admin',[{ role: "root", db: "admin" }]), and that makes me confused. I'm not authorised to run a command, and yet I can run a command to make myself root, and then run that command. Very strange :SGerkman
for those in which db.grantRolesToUser('admin',[{ role: "root", db: "admin" }]) didn't work, make sure you switch back to use admin... had the same issue, once I switched back it worked like a charmHare
Why are you using root instead of userAdminAnyDatabase in the role ?!Edlyn
I know the upstream docs mentions it and in case you're looking all over for it, to authenticate, you have to "use" the admin db like so: use admin; and then db.auth("username", "password"); Hope this helps someone.Cropper
From version 4.2 you can or even should use function passwordPrompt() i.e. something like this: db.createUser({user:"superuser", pwd:passwordPrompt(), roles:["root"]}). This is considered more secure than typing password that is visible on the screen. Be careful, password prompt is displayed only once. It does NOT ask you to retype your password. If you go with use admin then db: "admin" is not required.Pseudaxis
Yes, you need just to add role atlasAdmin in settingsWorkmanlike
I followed the steps above but under admin db inside compass I can only see temproles and tempusers which are empy. Why? Also under mongo shell show users it shows only the admin user and not ALL users from all dbs.Hygrophilous
If you wanna update just remove the userkey from the Object. db.updateUser('admin', { pwd: 'password', roles: [ { role: 'root', db: 'admin' } ] } );Gilliangilliard
M
49

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

Mercie answered 30/5, 2014 at 1:26 Comment(4)
I'm not sure this answer is relevant to the question, but either way it provides incorrect information. The dbOwner role includes the readWrite role: docs.mongodb.org/manual/reference/built-in-roles/#dbOwnerJourdain
the answer is correct - the dbadmin and useradmin roles (which is what the original poster asked about) do not include readWrite. The dbOwner does but that's not what the original poster was using and was asking about.Mercie
You're absolutely right. Apologies. I had spent too long wrangling roles and was befuddled.Jourdain
So you can have an admin user to access the actual mongodb server, and then have others for specific databases?Wincer
O
36

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
Orbadiah answered 4/5, 2016 at 14:21 Comment(1)
I get a Error: not authorized on admin to execute command when doing thisSamos
D
35

You can try: Using the --authenticationDatabase flag helps.

mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"
Derma answered 22/2, 2017 at 23:14 Comment(1)
If you don’t want to add roles to your users and only need this temporarily, this is the best approach.Pledgee
N
14

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 :)

Nigrosine answered 16/9, 2017 at 21:4 Comment(4)
So, if not root, then what role do you suggest to solve the problem?Beguile
Hi there @HendyIrawan , I would suggest that you decide on what exactly you want each of your users to be able to do and give them the role that enables them to do only that. For example if you only want a user to read (which is what the question tries to do with show collections) you should give it that ability and nothing else roles: [ { role: "read", db: "admin" } ]. Notice that the role here is read, this is database specific and you cannot do anything but that. Check out this link for other roles docs.mongodb.com/manual/reference/built-in-rolesNigrosine
So the answer to the question here (not "for example") is "read"?Beguile
Yes. Note that the user will only have the ability to read the db specified.Nigrosine
G
9

It's a simple question.

  1. It's important that you must switch the target db NOT admin.

use yourDB

  1. check your db authentication by

show users

  1. 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" }])

Gombroon answered 27/9, 2018 at 11:52 Comment(0)
W
4
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" 
    ]
    }
    )
Wellestablished answered 1/10, 2019 at 8:41 Comment(1)
Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.Holograph
S
4

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

Sherlene answered 10/3, 2022 at 10:50 Comment(0)
A
3

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:

  1. Choose your project in the MongoDB atlas website
  2. Connect/Connect with MongoDB Compass
  3. Download Compass/Choose your OS
  4. I used Compass 1.12 or later
  5. Copy the connection string under the Compass 1.12 or later.
  6. Open MongoDB Compass/Connect(top left)/Connect To
  7. Connection String detected/Yes/
  8. Append your project name after the hostname: cluster9-foodie.mongodb.net/projectname
  9. Connect & Tested the API with POSTMAN.
  10. Succeed.

Use the same connection string in your code too:

  1. Before:
    • mongodb+srv://projectname:password@cluster9-foodie.mongodb.net/admin
  2. After:
    • mongodb+srv://projectname:password@cluster9-foodie.mongodb.net/projectname

Good luck.

Anglomania answered 3/3, 2019 at 16:27 Comment(0)
P
1

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

Profitable answered 30/6, 2020 at 23:8 Comment(0)
C
0

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!

Cullen answered 7/2, 2016 at 19:39 Comment(1)
I don't know why this answer was downvoted; this is a legitimate suggestion. For example, I've run into a management console that was running Tomcat under the hood. If you start a local server (of any type) you'll likely check if it's running by trying to connect to it. That first connection will succeed. You'll then wrestle with the "hidden" server before checking your server's logs and noticing that your server couldn't bind to the desired port.Aleksandr
A
0

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.

Antlia answered 26/8, 2016 at 14:13 Comment(0)
P
0

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

Parlour answered 7/6, 2019 at 13:2 Comment(0)
S
0

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/

Silda answered 26/6, 2019 at 21:34 Comment(0)
V
0

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

Vexillum answered 16/10, 2020 at 19:45 Comment(1)
You could add this as a comment.Cham
S
-3

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

Schlesinger answered 21/9, 2020 at 14:56 Comment(0)
D
-12

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

Dichy answered 22/3, 2016 at 5:17 Comment(2)
The user says explicitly that he want to start using authorization thus he uncommented auth=true. Why do you suggest to disable authorization !?Raven
I guess ya didn't read the problem...OP wants auth, a combination of s-hunter's response for setting the user and jremi's for connecting to a custom configurationFob

© 2022 - 2024 — McMap. All rights reserved.