在Mongo .NET 2.0驱动程序中捕获MongoAuthenticationException

时间:2015-08-06 16:07:59

标签: c# .net mongodb authentication exception

我正在进行基于.NET 2.0驱动的MongoDB项目,该项目涉及对MongoDB的身份验证。我正在做的事情有一个示例代码:

public static bool createConneciton(string login, SecureString pass, string authDB) {
    var settings = new MongoClientSettings {
        Credentials = new[] {
            MongoCredential.CreateCredential(authDB, login, pass)
        },
        Server = new MongoServerAddress("my.mongodb.server", 27017)
    };
    mongoClient = new MongoClient(settings);
    return true;
}

if (Mongo.createConneciton(textBoxUsername.Text, pass, textBoxAuthDatabase.Text))
    Task<BsonDocument> results = Mongo.getNodeStats();

public static async Task<BsonDocument> getNodeStats() {
    try {
        var db = Mongo.mongoClient.GetDatabase("admin");
        var command = new BsonDocument {
            {"serverStatus",1}
        };
        BsonDocument result = await db.RunCommandAsync<BsonDocument>(command).ConfigureAwait(false);
                return result;
    }
    catch (Exception ex)
    {
        Logging.Log(ex);
        return null;
    }
}

到目前为止我遇到的主要问题是处理用户的凭据。因为所有操作都是惰性的,只有在getNodeStats()方法中执行时才会打开连接。因此,如果用户键入错误的凭据,他将等待30秒,因为而不是MongoDB.AuthenticationException甚至MongoDB.ConnectionException方法只会进入System.Timeout异常。如果您查看异常文本,这两个文本非常明显,两者都会升级但不会被捕获。

"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

我的第一个想法是强制打开连接,一旦用户键入它们并检查连接按钮而不是等待执行任何命令,就检查凭据,但显然MongoClient类不再具有.Open()方法。因此,如果它似乎不可能,我至少想要捕获AuthenticationException而不需要等待超时,但出于想法我应该尝试捕获它。

1 个答案:

答案 0 :(得分:1)

您无法使用 MongoCredential.CreateCredential 连接mongodb。您必须使用 MongoCredential.CreateMongoCRCredential 方法连接数据库。因为前一个凭证使用SCRAM-SHA-1机制来连接db,所以在.NET中会失败。我之所以没说清楚。

使用 MongoCredential.CreateMongoCRCredential ,您在mongodb中更改了&#34; authSchema&#34; 设置。您可以参考MongoDB-CR Authentication failed