【问题标题】:Error on MongoDB AuthenticationMongoDB 身份验证错误
【发布时间】:2017-11-14 18:38:36
【问题描述】:

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

使用 CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode : Primary } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } } 选择服务器 30000 毫秒后发生超时。集群状态的客户端视图是 { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "123.123.123.123: 27017“}”,端点:“123.123.123.123:27017”,状态:“断开连接”,类型:“未知”,HeartbeatException:“MongoDB.Driver.MongoConnectionException:打开与服务器的连接时发生异常。--- > MongoDB.Driver.MongoAuthenticationException:无法使用 sasl 协议机制 SCRAM-SHA-1 进行身份验证。---> MongoDB.Driver.MongoCommandException:命令 saslStart 失败:身份验证失败.. 在 MongoDB.Driver.Core.WireProtocol.CommandWireProtocol@987654321 @1 回复)在 MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.d__11.MoveNext() --- 从先前抛出异常的位置结束堆栈跟踪---在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotificat离子(任务任务)在 MongoDB.Driver.Core.Authentication.SaslAuthenticator.d__7.MoveNext() --- 内部异常堆栈跟踪结束 --- 在 MongoDB.Driver.Core.Authentication.SaslAuthenticator.d__7.MoveNext() - -- 从先前抛出异常的位置结束堆栈跟踪 --- 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 MongoDB.Driver.Core 的 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) .Authentication.AuthenticationHelper.d__1.MoveNext() --- 在 System.Runtime.CompilerServices.TaskAwaiter 的 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 处从先前引发异常的位置结束堆栈跟踪。 MongoDB.Driver.Core.Connections.ConnectionInitializer.d__3.MoveNext() 处的 HandleNonSuccessAndDebuggerNotification(Task task) --- 从先前引发异常的位置结束堆栈跟踪 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Tas k task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at MongoDB.Driver.Core.Connections.BinaryConnection.d__48.MoveNext() --- End of internal exception stack trace --- at MongoDB.Driver。 Core.Connections.BinaryConnection.d__48.MoveNext() --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 处的 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 处从先前引发异常的位置结束堆栈跟踪。 .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 项目中创建的数据库名称。

如何解决这个问题?

【问题讨论】:

  • 该错误意味着您提供了不正确的身份验证凭据。检查您的用户名和密码是否有效。如果您相信您这样做并且可以验证这些凭据是否允许您从另一个客户端(例如 mongo shell)进行连接,那么请在您与您的问题建立连接的位置包含代码。这比堆栈跟踪更有用。
  • 我可以通过 Robomongo 连接到 mongodb 服务器,但是在 c# 代码中它无法连接。
  • 这个项目是 Grandnode,它已经在里面了。
  • 在 Mongodb 日志中,它表示客户端 111.111.111.111:12312 的 Grandnode 上的 usernameexample 的 SCRAM-SHA-1 身份验证失败; UserNotFound: 找不到用户 usernameexample@Grandnode 但 Grandnode 是我想在 Grandnode 项目中创建的数据库名称。如何解决这个问题?

标签: c# mongodb


【解决方案1】:

是的,

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 上启用身份验证协议(和用户非默认端口)并重新启动 (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://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

代码:

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

    }
}

【讨论】:

    【解决方案2】:

    看起来您在连接时没有设置凭据,请添加此块 -

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

    【讨论】:

    • 这帮助我解决了使用 .net core 2 和 2.6 版本驱动程序的问题。
    【解决方案3】:

    可能有几个原因。我遇到了同样的问题,并通过在连接字符串中设置 解决了它:

    mongodb://<username>:<password>@<server_address>:<port>/<database_name>
    

    【讨论】:

    • 或者这个.... mongodb://myUser:myPassword@servername:27017?authSource=database_name
    【解决方案4】:

    我在 Azure 托管的 MongoDb (Cosmos Db) 中遇到了类似的错误。原来是网络设置让我阻止了所有访问。将其更改为允许从“所有网络”访问解决了该问题。

    该错误非常具有误导性,我预计会出现连接超时。

    在选择服务器 30000 毫秒后发生超时 CompositeServerSelector{ 选择器 = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }。集群状态的客户端视图是 { ClusterId : "1", ConnectionMode :“ReplicaSet”,类型:“ReplicaSet”,状态:“断开连接”,服务器: [{ ServerId: "{ ClusterId: 1, EndPoint: “未指定/XXXX.documents.azure.com:10255”}”,端点: “未指定/XXXX.documents.azure.com:10255”,状态:“断开连接”, 类型:“未知”,HeartbeatException: “MongoDB.Driver.MongoConnectionException:发生异常时 打开与服务器的连接。 ---> MongoDB.Driver.MongoAuthenticationException: 无法进行身份验证 使用 sasl 协议机制 SCRAM-SHA-1。 ---> MongoDB.Driver.MongoCommandException:命令 saslContinue 失败:不是 已通过身份验证

    为了解决问题,我也尝试了 MongoDb Compass,但也没有用,告诉我这不是代码。

    【讨论】:

    • 这确实很误导人。谢谢你拯救我的一天;-)
    【解决方案5】:

    在我的情况下,这是一个权限问题。

    将连接字符串从 ?retryWrites=true&amp;w=majority 更改为 ?authSource=admin 并且成功了。

    这个错误是关于权限的。因此,请确保凭据正确无误且没有错字并拥有适当的权限。

    【讨论】:

      【解决方案6】:

      来不及回复答案,但由于这没有任何正确答案,这是我发现的

      为了解决此错误,应检查一些事项。

      1. 通过查看网络访问(mongo atlas 仪表板的左侧边栏)检查您的 IP 是否允许,如果您只是为了测试,那么还有允许所有用户的选项。
      2. 检查数据库访问(在mongo atlas仪表板左侧边栏),如果看到用户,请尝试更改密码(与您的登录密码不同),默认为空。

      我尝试了这两个步骤,它对我有用。

      【讨论】:

        【解决方案7】:

        访问通常包含在 /var/log/mongodb/mongod.log 中的日志文件可能会很有用。您可以在那里发现访问错误的原因。 在我的情况下,我使用机器 IP 访问数据库,而不是“localhost”或“127.0.0.1”,所以我的用户地址没有被授权,问题中描述了同样的错误。

        在这种情况下,使用扩展的 createUser 命令:

        db.createUser(
        {
           user:"myuser",
           pwd:"mypassword",
           roles:[{role:"readWrite",db:"mydb"}],
           authenticationRestrictions:[{clientSource:["127.0.0.1","localIP"]}],
           mechanisms:["SCRAM-SHA-1","SCRAM-SHA-256"]
         }
        )
        

        【讨论】:

          猜你喜欢
          • 2016-06-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多