c# - MongoDB 身份验证错误

连接到 Mongodb 时出现此错误。我不太确定这是什么错误。

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

谁能帮帮我?

我使用的是 MongoDB 版本 3.4.4。

请,谢谢。

在 Mongodb 日志中,它说

来自客户端 111.111.111.111:12312 的 Grandnode 上的 usernameexample 的 SCRAM-SHA-1 身份验证失败; UserNotFound: 找不到用户 usernameexample@Grandnode

但 Grandnode 是我想在 Grandnode 项目中创建的数据库名称。

如何解决这个问题?

最佳答案

是的,

MongoDb....花 6 小时寻找如何制作正确的安全 MongoDB 连接字符串。

于 2020 年 8 月 25 日在 MongDB 4.4.0 社区版上使用 MognoDb.Driver 2.10.3 进行测试。

报告错误

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

解决方案

  1. 使 MongoDB 数据库用户具有正确的权限

    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. 在 C:\P F\MongoDB\bin\mongod.cfg 中启用 MongoDB 上的身份验证协议(protocol)(和用户非默认端口)并重新启动 (Windows) 数据库服务以加载这些设置

     # 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. 修正 MongDB 连接字符串

引用:

https://learn.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

代码:

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

    }
}

https://stackoverflow.com/questions/44513786/

相关文章:

java - 从 JAVA 应用程序使用 SSL 连接到 MongoDb

node.js - Mongoose 复合索引创建字段顺序

javascript - 如何在 Node 议程中以编程方式定义多个具有相同名称的作业

node.js - mongoose.connection.collections.collecti

javascript - 如何将文件名设置为与数据库中的对象 ID 相同?

mongodb - 如何为 mongodb 副本集配置 grails 3

mongodb - 语法错误 : missing ) after argument list @(s

linux - 从 bash 提示符和脚本向 docker exec 传递参数

node.js - Mongoose(或类似的 ODM)内存记录注册表?

mongodb - 为什么 mongo dot notation 会替换整个子文档?