MongoDB-CR Authentication failed - mongodb

I am getting following error while authenticating user : purchase_user#purchase failed. MongoDB-CR Authentication failed. Missing credentials in user document when I access webservice through browser.
But I am able to authenticate purchase_user from mongo it returns 1 .

go to mongoDB console and delete your current user & set authSchema version to 3 instead of 5 , follow these commands in mongo console -
mongo
use admin
db.system.users.remove({}) <== removing all users
db.system.version.remove({}) <== removing current version
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
Now restart the mongod and create new user then it should work fine.
Note: use remove commands in test db only, if in production use update.
Authentication information for Kubernetes Helm Chart
If you delete the all users and authentication is enabled in the configuration (or --auth param which is set per default on the Kubernetes helm chart), it's not possible to access MongoDB any more. Its required to disable authentication, create a new user and then re-enable it.
On Kubernetes you need to edit the parameters and add --noauth as argument, since it's not the default there as on a classic installed MongoDB. Please see the CLI documentation for more information about --noauth and the corresponding --auth.

Had the same issue. What was happening to me was that when I use MongoDB 3 to create my user, it was using SCRAM-SHA-1 as it's authentication mechanism instead of MongoDB-CR. What I had to do was:
List item
Delete the created user.
Modify the collection admin.system.version such that the authSchema's currentVersion is 3 instead of 5 (3 is using MongoDB-CR).
Recreate your user.
Should work without problems now.

The step number 2. above is not detailed explicitly, I found this solution and worked for me.
var schema = db.system.version.findOne({"_id" : "authSchema"})
schema.currentVersion = 3
db.system.version.save(schema)

I think this is the answer you need:
1) Start 3.0 without auth enabled. (Auth needs to be disabled otherwise you'll get the not authorized error).
2) Run (after selecting "admin"use db):
var schema = db.system.version.findOne({"_id" : "authSchema"})
schema.currentVersion = 3
db.system.version.save(schema)
3) restart mongodb with auth enabled.
4) Create a new admin user (the old one, the one you created before this workaround won't work).
Things should work now. This issue was driving me crazy as well.
Answer came from here: https://jira.mongodb.org/browse/SERVER-17459

Adding to above solution by Vivek & explanation taken from here
use admin
db.system.users.remove({}) <== removing all users
db.system.version.remove({}) <== removing current version
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
you only need to downgrade the schema to create MONGODB-CR users.
Once they are there the old drivers will work regardless of the value
of authSchemaVersion. However if you run authSchemaUpgrade to change
from "3" to "5" the users will obviously be upgraded.
My comment regarding new users was that if you have existing SCRAM
users and change the schema manually to "3" the user documents won't
be consistent with the new schema. This is not enforced however but
the SCRAM users will still work for any driver supporting SCRAM.

Upgrade mongo-java-driver to 3.0.3 and use :-
MongoCredential.createScramSha1Credential instead of MongoCredential.createMongoCRCredential
MongoCredential createMongoCRCredential = MongoCredential.createScramSha1Credential(mongoConfiguration.getDatabaseUserName(), mongoConfiguration.getAuthenticationDatabase(),mongoConfiguration.getDatabasePassword().toCharArray());
http://docs.mongodb.org/master/release-notes/3.0-scram/

For me I was using a mongo 2 client trying to connect to a mongo 3 server. Upgrading the client fixed the issue.

I was getting this error as well.
Check your Spring Config file.. I had a constructor arg named "MONGODB-CR" which I swapped to "SCRAM-SHA-1" and it fixed my issue.
tailing the mongodb log file helped me diagnose this.

uninstall mongodb-clients packages provided by Ubuntu
install mongodb-org-shell provided by official MongoDB
This solved the problem, because The unofficial mongodb package provided by Ubuntu is not maintained by MongoDB. You should always use the official MongoDB mongodb-org packages, which are kept up-to-date with the most recent major and minor MongoDB releases.

Probably old news, and problem solved, but adding my experience with the same error:
I had the exact same problem (using MongoDB 3.0), and a C# driver that was setup to use a pre 3.0 db.
In C# I used "MongoDB.Driver.CreateMongoCRCredentials()", which caused the error the OP was getting.
The fix (for me), was to switch the command above to "MongoDB.Driver.CreateCredential()".
I guess this could be caused by using "old" users (from pre 3.0) on an upgraded system. Which either forces you to upgrade your users to the new authentication mechanism, or downgrade the authentication mechanism on your server.

June 2018 I got this error after trying to connect to my Mongodb version 3.6 from an ancient client installed in /usr/bin. I installed the mongo DB in a separate folder outside of the OS standard directory, and so my installation was conflicting with the ancient version installed by the package manager.

For those who is struggling to update auth schema (see the accepted answer) in MongoDB 3.6 due to the not authorized on admin to execute command and removing FeatureCompatibilityVersion document is not allowed errors, this is what's worked for me.
To resolve the first error:
> db.system.version.remove({})
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on admin to execute command { update: \"system.version\", ordered: true, lsid: { id: UUID(\"58e86006-d889-440a-bd83-ad09fcd81747\") }, $db: \"admin\" }"
}
})
I had to create a custom role that permits any action on any resource and a user with this role, then login to the admin database with that new user:
mongo admin
db.createUser({user: 'admin', pwd: 'mypwd', roles: ['root']})
exit
mongo admin -u admin -p
db.createRole({role: 'fullaccess', privileges: [{resource: {anyResource: true}, actions: ["anyAction"]}], roles: []})
db.createUser({user: 'superadmin', pwd: 'mypwd', roles: ['fullaccess']})
exit
mongo admin -u superadmin -p
(Just using the admin user with root role or disabling security.authorization in config didn't work for me and still had the same error when trying to update the system.version table.)
After that I had another error:
> db.system.version.remove({})
WriteResult({
"nRemoved" : 0,
"writeError" : {
"code" : 40670,
"errmsg" : "removing FeatureCompatibilityVersion document is not allowed"
}
})
To resolve it, we should only update the authSchema document instead of removing the whole collection.
(Generally speaking, you shouldn't blindly remove everything from system tables in production and always check what would be the implications of updating them, so that's another reason to update the needed record only.)
db.system.version.update({"_id": "authSchema"}, {currentVersion: 3})
Now you should be able to create a user with the old authentication mechanism. You also might need to switch to your database first, so that the user is created in that database rather than in admin one. Otherwise you'd have to use the authSource=admin parameter in your connection string.
(I'm actually lying here - it still will be created in admin database, just with mydb.myuser id instead of admin.myuser. But I use the same way of describing these things that's being used in MongoDB documentation. I suppose this is how it actually used to work in previous versions and in general we shouldn't care about the internal implementation details.)
use mydb
db.createUser({user: 'myuser', pwd: 'mypwd', roles: [{role: 'dbOwner', db: 'mydb'}]})
And don't forget to cleanup:
use admin
db.system.version.update({"_id": "authSchema"}, {currentVersion: 5})
exit
mongo admin -u admin -p
db.dropUser('superadmin')
db.dropRole('fullaccess')
You may want to keep the admin user - I was not able to create it again even with security.authorization setting disabled. It looks like if there are any records in admin.system.users table, the setting does not work anymore and mongo requires authentication to do something.

I had the same error with a Spring Boot app using a new MongoDB 3.2.8 database. By upgrading to the latest version of the Java Mongo driver (3.2.2) and then adding the authentication mechanism param to the URI in my application.properties, I was able to get it working:
spring.data.mongodb.uri=mongodb://myusername:mypassword#localhost/?authSource=admin&authMechanism=SCRAM-SHA-1
spring.data.mongodb.database=test

Related

How do you set up authentication in mongoDB compass? Every solution uses the mongod terminal not the compass terminal

What I am trying to do:
I want to have my schema require a log in to order to gain access
From my understanding, you must first use the --auth flag to enable authorization. When I do this in the compass shell, it says auth is not recognized/defined
I want to be able to create new users with different sets of permissions
Neither of the create user commands listed below work for me
My suspicions on the issue:
I think the reason I am struggling might be because I am on a local host connection provided by the MongoDB compass. I am new to MongoDB and am just practicing. My connection URI is mongodb://localhost:27017
Things I have tried:
Using the advanced connection options in compass GUI
Running the below in test and admin
// running:
--auth
db.auth()
db.createUser({user: "max", pwd: "max", roles: ["userAdminAnyDatabase"]})
db.createUser({
user: "max",
pwd: "max",
roles: [{role: "userAdminAnyDatabase", db: "admin"}, {"readWriteAnyDatabase"}]
})
The create functions give this error:
clone(t={}){const r=t.loc||{};return e({loc:new Position("line"in r?r.line:this.loc.line,"column"in r?r.column:...<omitted>...)} could not be cloned.
I'm going to attempt an answer based on the discussion in the comments. There are definitely still some things that I am not clear on, so please do add additional details to help clarify.
the mongod terminal is something different. It used to be installed with MongoDB, but no longer is by default. All the videos I see are old and working in the mongod terminal not the MongoDB compass shell
You are correct that the earlier shell (mongo) that used to ship with the database no longer does. It has been replaced with a newer one (mongosh) which is still functionally mostly the same, but with some additional expanded capabilities. You can mostly still use the older shell to connect to MongoDB though there really shouldn't be any reason for doing so.
It is the newer mongosh utility that is now bundled with Compass.
You can see here that the db.createUser() method is included as one of the mongosh Methods in the navigation on the left side of the page. So that method and functionality should be present in this newer shell.
I believe it is all just stored locally.
This comment doesn't really make sense. It's true that MongoDB credentials are stored by the cluster itself so it is "local" in that regard. But nothing is going to be stored outside of that such as in Compass or on your local machine.
I do not believe it's connected to atlas
What are the actual connection settings you used when opening Compass to connect to a system?
To get back to the original request, what is the actual outcome that you are seeing when running those commands? Are you getting an error message or?
Knowing that would allow us to troubleshoot further. If you do happen to be running these commands against an Atlas cluster and seeing that the users don't exist shortly after doing so, then you will want to use the Atlas interface instead.
Edit
Based on the updated question, it seems part of the confusion is around what and where to run some commands.
Working backwards, the specific error that you mention is caused by a syntax error. In your array of roles the second entry should either just be a string or a fully-formed object. So try changing
roles: [{role: "userAdminAnyDatabase", db: "admin"}, {"readWriteAnyDatabase"}]
to
roles: [{role: "userAdminAnyDatabase", db: "admin"}, {role:"readWriteAnyDatabase",db:"admin"}]
Also I see now that you seem to be adding the --auth flag to the commands that are being run in the shell. This is incorrect. Rather that is a parameter that is included when you start the mongod process, see here. You can still create users without mongod enforcing authentication, but you'll want to restart the mongod process itself with the right configuration (eg with --auth) to actually prevent users from interacting with the data without properly authenticating.

Mongodb not authenticating on localhost or connecting authenticated mongodb compas

System
Hi I am running mongodb on ubuntu 20.14.
Im running mongodb with systemctl
What I've done
I've tried to make it more secure by adding an admin user and enabled authentication.
Ive restarted the service multiple times.
config file:
security:
authorization: enabled
How I created user:
use admin
db.createUser({
user: "username",
pwd: "123456",
roles:["root"]
})
Problem
I am still able to connect through mongodb compass without any auth??? Im able to do everything even tho I enabled the authentication?
I am not able to login authenticated using these urls:
mongodb://username:password#localhost:27017/
mongodb://username:password#localhost:27017?authSource=admin
Im sure the config file is loading since authentication works in console and I can see the right config load in the mongod.log
It would be this one:
mongodb://username:password#localhost:27017?authSource=admin
See also: Authentication failure while trying to save to mongodb
Yes, even without authentication you can connect to Mongo database in any case. However, apart from harmless commands like db.help(), db.version(), db.getMongo(), etc. you cannot execute anything.
You can skip parameter enableLocalhostAuthBypass. The localhost exception applies only when there are no users created in the MongoDB instance.
Solution
I thought the issue was with mongodb compass.
So what I did was deleting the application and when I did that I saw that I had mongodb installed on my pc too.
I was never connecting to the mongodb that I have created on my ubuntu server but on my own pc.

Error 13 when trying to authenticate to MongoDB

I'm trying to connect to MongoDB through JDBC. The connection string is like below,
mongodb://localhost:27017/games?authSource=admin
However I'm getting the following trace:
{ "ok" : 0.0, "errmsg" : "not authorized on admin to execute command { listDatabases: 1 }", "code" : 13 }
My intention is not listing all the databases, but the user has to authenticate against admin database and can read/write on games database. What mistake I'm making here?
I want user X to authenticate against admin DB but read just games DB so not sure why it asks for listDatabase privilege.
First, I assume you are using the MongoDB Java Driver, which is actually not JDBC.
It would be helpful for you to share:
How you created your user
The Java code that you are executing
The version of mongo-java-driver and MongoDB that you are using
But based on the error, it appears that you are successfully authenticating. I strongly suspect that you are either directly calling listDatabases() or listDatabaseNames().
The other thing that does not look quite right is the fact that you are specifying authSource=admin in your MongoClientURI. But that issue should have given you an Autentication Failed error. You should be either leaving the authSource off of the connection string or specify authSource=games.
Based on what you described, when you created your user, you should have created the user in the games database (users will actually be stored in the admin database, but you would be authenticating against the games database).

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.

Mongo authentication issues

Hello i have a new AWS server with a Bitnami MEAN stack.
I'm root user on the server, and i started up mongo on the command line.
when i try to do anything (other than "use test" , or "use admin"), such as "show dbs"
I get the following error:
show dbs
listDatabases failed:{ "ok" : 0, "errmsg" : "unauthorized" } at src/mongo/shell/mongo.js:46
I know i'm doing something wrong with regard to permissions, i just dont' know what it is.
when I looked at the mongodb.config, everything looks ok, but i see:
# Turn on/off security. Off is currently the default
#noauth = true
auth = true
Also, possibly relevant, when i try to run mongod, I get errors about "/data/db" doesn't exist, or if i make the directory, I get "not enough space issues"
thank you for your time.
You should not need to run mongod again if it is already running, and chances are that it already is. You are also not saying how you are trying to connect, which is likely your problem.
I would suggest reading the relevant documentation which explains what the default user authentication is and how to connect:
$ mongo admin --username root --pasword YOURPASSWORD
Where the default password is contained in the documentation page. There is also information on setting up new user for your application.
For more information, see the official MongoDB documentation which has many examples:
http://docs.mongodb.org/manual/administration/security-access-control/
You are able to successfully connect to database but you does not have admin privilege for this.
If you know the admin user id and password,You can authenticate by
db.auth("user_name",'passwd');