MongoDB C#驱动程序停止身份验证失败重试

时间:2018-10-05 16:36:27

标签: c# mongodb mongodb-.net-driver

仅学习如何使用MongoDB C#驱动程序,并且想知道为什么“ MongoClient”尝试使用错误的凭据连续重新连接?

如何停止自动连接并处理“ MongoAuthenticationException”,以便用户可以尝试重新登录?

namespace MongoDBConsole
{
internal class Program
{
    public static void Main(string[] args)
    {
        MainAsyc().Wait();

        Console.ReadLine();
    }

    static async Task MainAsyc()
    {
        var pw = "admin";
        var sPwd = new SecureString();
        foreach (var c in pw)
        {
            sPwd.AppendChar(c);
        }

        var settings = new MongoClientSettings()
        {
            Credential = MongoCredential.CreateCredential("admin", "admin", sPwd)
        };

        var client = new MongoClient(settings);
    }
}

}

Mongo日志

2018-10-06T02:33:00.354+1000 I NETWORK  [conn3] received client metadata from 127.0.0.1:53063 conn3: { driver: { name: "mongo-csharp-driver", version: "2.7.0.0" }, os: { type: "Windows", name: "Microsoft Windows 10.0.17134", architecture: "x86_32", version: "10.0.17134" }, platform: ".NET Framework 4.7.3163.0" }
2018-10-06T02:33:00.409+1000 I ACCESS   [conn3] SASL SCRAM-SHA-256 authentication failed for admin on admin from client 127.0.0.1:53063 ; AuthenticationFailed: SCRAM authentication failed, storedKey mismatch
2018-10-06T02:33:00.409+1000 I NETWORK  [conn3] end connection 127.0.0.1:53063 (0 connections now open)
2018-10-06T02:33:00.410+1000 I NETWORK  [listener] connection accepted from 127.0.0.1:53064 #4 (1 connection now open)
2018-10-06T02:33:00.410+1000 I NETWORK  [conn4] received client metadata from 127.0.0.1:53064 conn4: { driver: { name: "mongo-csharp-driver", version: "2.7.0.0" }, os: { type: "Windows", name: "Microsoft Windows 10.0.17134", architecture: "x86_32", version: "10.0.17134" }, platform: ".NET Framework 4.7.3163.0" }
2018-10-06T02:33:00.468+1000 I ACCESS   [conn4] SASL SCRAM-SHA-256 authentication failed for admin on admin from client 127.0.0.1:53064 ; AuthenticationFailed: SCRAM authentication failed, storedKey mismatch
2018-10-06T02:33:00.469+1000 I NETWORK  [conn4] end connection 127.0.0.1:53064 (0 connections now open)

1 个答案:

答案 0 :(得分:0)

对于遇到相同问题的任何人,我相信解决方案都是

client.cluster.dispose();
client = null

然后在需要时创建新客户端,例如新凭证

    var settings = new MongoClientSettings()
    {
        Credential = MongoCredential.CreateCredential("admin", "admin", sPwd)
    };

    var client = new MongoClient(settings);