13
votes

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?

6
The error means you supplied incorrect authentication credentials. Check you have a valid username and password. If you believe you do and can verify those credentials allow you connect from another client such as the mongo shell, then include the code where you are making the connection to your question. Which is of more use than a stack trace.Neil Lunn
I can connect to mongodb server through Robomongo but in c# code it cant connect.Desmond
This project is Grandnode and it already have in it.Desmond
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?Desmond

6 Answers

7
votes

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");
            }
        }

    }
}
6
votes

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);
5
votes

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>
4
votes

I have had a similar error with my Azure hosted MongoDb (Cosmos Db). It turned out to be network settings such that I had blocked all access. Changing it to Allow access from "All networks" fixed the issue.

The error is very misleading, I would have expected a connection timeout.

A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/XXXX.documents.azure.com:10255" }", EndPoint: "Unspecified/XXXX.documents.azure.com:10255", 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 saslContinue failed: Not Authenticated.

To troubleshot I tried from MongoDb Compass as well and that didn't work either, showing me it wasn't the code.

0
votes

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.

0
votes

It's too late to reply the answer, but since this does not have any correct answer, here is what I found out

There are some things which should be checked in order to resolve this error.

  1. Check weather you IP is allowed by viewing Network Access(left sidebar of mongo atlas dashboard), if you are doing only for testing, then there is option to allow all user also.
  2. Check Database Access( on the left sidebar of mongo atlas dashboard), if you see a user, try changing the password(it's not same as your login password), by default it's empty.

I tried these two steps and it worked for me.