Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error on MongoDB Authentication

Tags:

c#

mongodb

I am getting this error when connecting to Mongodb. I not really sure what is this error.

A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode : Primary } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "123.123.123.123:27017" }", EndPoint: "123.123.123.123:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1. ---> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed.. at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol1.ProcessReply(ConnectionId connectionId, ReplyMessage1 reply) at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.d__11.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at MongoDB.Driver.Core.Authentication.SaslAuthenticator.d__7.MoveNext() --- End of inner exception stack trace --- at MongoDB.Driver.Core.Authentication.SaslAuthenticator.d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at MongoDB.Driver.Core.Authentication.AuthenticationHelper.d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at MongoDB.Driver.Core.Connections.ConnectionInitializer.d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at MongoDB.Driver.Core.Connections.BinaryConnection.d__48.MoveNext() --- End of inner exception stack trace --- at MongoDB.Driver.Core.Connections.BinaryConnection.d__48.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at MongoDB.Driver.Core.Servers.ServerMonitor.d__27.MoveNext()" }] }

Can anyone help me out?

I am using MongoDB version 3.4.4.

Please and thank you.

In the Mongodb Log, it says that

SCRAM-SHA-1 authentication failed for usernameexample on Grandnode from client 111.111.111.111:12312 ; UserNotFound: Could not find user usernameexample@Grandnode

but Grandnode is the database name that I want to create in Grandnode project.

How to solve this problem?

like image 835
Desmond Avatar asked Jun 13 '17 06:06

Desmond


4 Answers

Yes,

MongoDb....spend 6hrs on finding how to make correct secure MongoDB connection-string.

Tested with on 25/08/20 with MognoDb.Driver 2.10.3 on MongDB 4.4.0 Community Edition.

Reported Error

Error:
"Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","principalName":"MyUser","authenticationDatabase":"mydb","client":"127.0.0.1:2012","result":"UserNotFound: Could not find user \"MyUser\" for db \"mydb\""}}
Cause:  
Did not specify authentication database: private string _authDbName = "admin";

Error:
"Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","principalName":"MyUser","authenticationDatabase":"admin","client":"127.0.0.1:2012","result":"UserNotFound: Could not find user \"MyUser\" for db \"mydb\""}}
Cause:
Did not specify authentication mechanism, today "SCRAM-SHA-1", tomorrow default should become "SCRAM-SHA-256":        private string _authMechanism = "SCRAM-SHA-1";

Error:
"Checking authorization failed","attr":{"error":{"code":13,"codeName":"Unauthorized","errmsg":"not authorized on admin to execute command { dbStats: 1, lsid: { id: UUID(\"dc5ce829-f1a1-40c0-bb02-1caabe73c90a\") }, $db: \"admin\" }"}}}
Cause:
Did not gave permissions to MongoDB user to read the admin database to verify authorisation: db.grantRolesToUser("MyUser",[{ role: "read", db: "admin" }])

Error:
'mongodb://127.0.0.1:30017' is not a valid end point. (parameter 'value')
Cause:
Micosoft documentation tricked me in typo _host is not "mongodb://127.0.0.1" but only hostname or ip-addres, of course;   private string _host = "127.0.0.1";

Solution

  1. make MongoDB database user with correct privs

    https://docs.mongodb.com/manual/tutorial/manage-users-and-roles/

     c:\>mongo --host 127.0.0.1 --port 27017
     >
     db.createUser(
           {
             user: "MyAdmin",
             pwd: "MyAdminPassw0rd",
             roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
           }
         )
    
         db.createUser(
           {
             user: "MyRoot",
             pwd: "MyRootPassw0rd",
             roles: [ { role: "root", db: "admin" } ]
           }
         )
    
         db.createUser(
           {
             user: "MyUser",
             pwd: "MyUserPassw0rd",
             roles: [ { role: "readWrite", db: "mydb" } ]
           }
         )
    
        // if done later; reconnect as "MyAdmin" and allow "MyUser" read on authentication database "admin"
    
         use admin
         db.grantRolesToUser(
         "MyUser",
         [
           { role: "read", db: "admin" }
         ]
         )
    
  2. enable authentication protocol (and user non-default port) on MongoDB in C:\P F\MongoDB\bin\mongod.cfg and restart your (Windows) database Service to load these settings

     # mongod.conf
    
     # for documentation of all options, see:
     #   http://docs.mongodb.org/manual/reference/configuration-options/
    
     # network interfaces
     net:
       port: 30017
       bindIp: 127.0.0.1
    
     security:
       authorization: "enabled"
    
     # to connect from now on user user & password 
     # c:\>mongo --host 127.0.0.1 --port 30017 --authenticationDatabase admin -u "MyAdmin" -p "MyPassw0rd"
    
  3. make correcte MongDB connection-string

references:

https://docs.microsoft.com/en-us/azure/cosmos-db/create-mongodb-dotnet#update-your-connection-string

https://github.com/Azure-Samples/azure-cosmos-db-mongodb-dotnet-getting-started/blob/master/MyTaskListApp/DAL/Dal.cs

code:

using System;
using MongoDB.Driver;
using System.Security.Authentication;
 
namespace MyApp.Repositories
{
    public class DbContext
        {
        private readonly IMongoDatabase _mongoDb;
        private string _host = "127.0.0.1";
        private Int32 _port = 30017;
        private string _userName = "MyUser";
        private string _password = "MyUserPassw0rd";
        private bool _userTls = false;                  //TODO enable MongoDB Server TLS first, then enable Tls in client app
        private string _authMechanism = "SCRAM-SHA-1";
        private string _authDbName = "admin";
        private string _dbName = "mydb";

        public DbContext()
        {

            MongoClientSettings settings = new MongoClientSettings();
            settings.Server = new MongoServerAddress(_host, _port);

            settings.UseTls = _userTls;
            settings.SslSettings = new SslSettings();
            settings.SslSettings.EnabledSslProtocols = SslProtocols.Tls12;

            MongoIdentity identity = new MongoInternalIdentity(_authDbName, _userName);
            MongoIdentityEvidence evidence = new PasswordEvidence(_password);

            settings.Credential = new MongoCredential(_authMechanism, identity, evidence);

            MongoClient client = new MongoClient(settings);
            _mongoDb = client.GetDatabase(_dbName);

        }
        
        public IMongoCollection<User> UserRecord
        {
            get 
            {
                return _mongoDb.GetCollection<User>("user");
            }
        }

    }
}
like image 124
Joris Avatar answered Sep 28 '22 04:09

Joris


Looks like you are not setting credentials while connecting, add this block -

string username = "user";
string password = "password";
string mongoDbAuthMechanism = "SCRAM-SHA-1";
MongoInternalIdentity internalIdentity = 
          new MongoInternalIdentity("admin", username);
PasswordEvidence passwordEvidence = new PasswordEvidence(password);
MongoCredential mongoCredential = 
     new MongoCredential(mongoDbAuthMechanism, 
             internalIdentity, passwordEvidence);
List<MongoCredential> credentials = 
           new List<MongoCredential>() {mongoCredential};


MongoClientSettings settings = new MongoClientSettings();
// comment this line below if your mongo doesn't run on secured mode
settings.Credentials = credentials;
String mongoHost = "127.0.0.1";
MongoServerAddress address = new MongoServerAddress(mongoHost);
settings.Server = address;

MongoClient client = new MongoClient(settings);          

var mongoServer = client.GetDatabase("myDb");
var coll = mongoServer.GetCollection<Employee>("Employees");

// any stubbed out class
Employee emp = new Employee()
{
    Id = Guid.NewGuid().ToString(),
    Name = "Employee_" + DateTime.UtcNow.ToString("yyyy_MMMM_dd")
};

coll.InsertOne(emp);
like image 44
Kev Avatar answered Sep 28 '22 06:09

Kev


There may be several reasons. I had the same problem and solved it with setup in connection string:

mongodb://<username>:<password>@<server_address>:<port>/<database_name>
like image 7
Anton Gorbunov Avatar answered Sep 28 '22 04:09

Anton Gorbunov


In my case it is a permission issue.

changed the connection string from ?retryWrites=true&w=majority to ?authSource=admin and it worked.

This error is all about permission. So make sure the credentials are correct and there is no typo and have proper permissions.

like image 6
Shubham Chadokar Avatar answered Sep 28 '22 06:09

Shubham Chadokar