Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch MongoAuthenticationException in Mongo .NET 2.0 Driver

I'm doing MongoDB project based on .NET 2.0 driver which involves authentication to MongoDB. There is a example code for what i'm doing:

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

Main problem i encountered so far is processing user's credentials. Because all operations are lazy and connection opens only on execution in getNodeStats() method. So if user types wrong credentials, he is going to wait for 30 seconds because instead of MongoDB.AuthenticationException or even MongoDB.ConnectionException method going to though only System.Timeout exception. If you look though text of exception that is quite obvious that both are rised but not catched.

"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

My first thought was to force open connection to check for credentials as soon as user typed them and hit connect button rather then waiting for any command to be executed, but apparently MongoClient class does not have .Open() method anymore. So if it does not seem to be possible i at least would like to catch AuthenticationException without need to wait for timeout, but out of ideas where should i try and catch it.

like image 206
JagdCrab Avatar asked Aug 06 '15 16:08

JagdCrab


1 Answers

You cannot connect mongodb using MongoCredential.CreateCredential.You have to use MongoCredential.CreateMongoCRCredential method to connect the db. Because the former credential use SCRAM-SHA-1 mechanism to connect db, in .NET which will fail. And the reason I have not make clear.

Using MongoCredential.CreateMongoCRCredential, you have change "authSchema" setting in mongodb. You can refer to MongoDB-CR Authentication failed

like image 55
AlanLiu Avatar answered Nov 16 '22 20:11

AlanLiu