MongoDB C#驱动程序检查身份验证状态&角色 [英] MongoDB C# Driver check Authentication status & Role

查看:61
本文介绍了MongoDB C#驱动程序检查身份验证状态&角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用MongoDB身份验证机制登录MongoDB的代码.

This is my code to login to MongoDB by using MongoDB Authentication Mechanisms.

try
{
    var credential = MongoCredential.CreateMongoCRCredential("test", "admin", "123456");
    var settings = new MongoClientSettings
    {
        Credentials = new[] { credential }
    };
    var mongoClient = new MongoClient(settings);
    var _database = mongoClient.GetDatabase("test");
    var collection = _database.GetCollection<Test>("book");
    var filter = new BsonDocument();
    var document = collection.Find(new BsonDocument()).ToList();
}
catch (Exception ex)
{
}

当我们在凭据中输入错误的用户名/密码时,如何检查登录结果?当前我无法检查它,我必须等待collection.Find().ToList()抛出TimeoutException,在这种情况下,它的身份验证失败.我们必须进行CRUD检查身份验证结果(通过捕获TimeoutException).这不是检查登录状态的好方法.

When we put wrong username/password in the Credential, how to check the login result? Currently I can't check it, I have to wait to collection.Find().ToList() throw an TimeoutException , and in this context it's authentication failed. We must make a CRUD to check the authentication result (by catching TimeoutException). It's not a good manner to check login status.

当我们输入正确的用户名/密码进行身份验证时,如何检查该数据库中的帐户角色?

And when we put right username/password to authenticate, how to check the account role in this database?

推荐答案

查看C#MongoDB客户端的源代码,MongoClient构造函数不会引发任何与连接相关的异常.仅当应用程序使用MongoClient在MongoDB服务器上执行某些操作时,才会引发异常.但是,正如您所发现的那样,该异常是一个通用的超时异常,表明驱动程序未能找到合适的服务器.由于异常本身确实包含有关故障的详细信息,因此您可以使用该信息来创建一种类似于以下方法的方法,以检查是否可以对数据库运行虚拟命令.在这种方法中,我将所有超时值减少到一秒钟:

Looking at the source code for the C# MongoDB client, the MongoClient constructors do not throw any connectivity-related exceptions. It's only when an application uses the MongoClient to perform some a on the MongoDB server that an exception will be thrown. However, as you discovered, that exception is a generic time-out exception indicating that the driver failed to find a suitable server. As the exception itself does contain details regarding the failure, you can use that information to create a method like the one below to check if you can run a dummy command against the database. In this method I have reduced all the time out values to one second:

public static void CheckAuthentication(MongoCredential credential, MongoServerAddress server)
    {
        try
        {
            var clientSettings = new MongoClientSettings()
            {
                Credentials = new[] {credential},
                WaitQueueTimeout = new TimeSpan(0, 0, 0, 1),
                ConnectTimeout = new TimeSpan(0, 0, 0, 1),
                Server = server,
                ClusterConfigurator = builder =>
                {
                    //The "Normal" Timeout settings are for something different. This one here really is relevant when it is about
                    //how long it takes until we stop, when we cannot connect to the MongoDB Instance
                    //https://jira.mongodb.org/browse/CSHARP-1018, https://jira.mongodb.org/browse/CSHARP-1231
                    builder.ConfigureCluster(
                        settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(1)));
                }
            };

            var mongoClient = new MongoClient(clientSettings);
            var testDB = mongoClient.GetDatabase("test");
            var cmd = new BsonDocument("count", "foo");

            var result = testDB.RunCommand<BsonDocument>(cmd);
        }
        catch (TimeoutException e)
        {

            if (e.Message.Contains("auth failed"))
            {
                Console.WriteLine("Authentication failed");
            }

            throw;
        }
    }

根据您的评论,您可以使用以下代码段查询给定用户的角色:

As per your comment you can query roles for a given user, using the snippet below:

var mongoClient = new MongoClient(clientSettings);
var testDB = mongoClient.GetDatabase("test");
string userName = "test1";
var cmd = new BsonDocument("usersInfo", userName);
var queryResult = testDB.RunCommand<BsonDocument>(cmd);
var roles = (BsonArray)queryResult[0][0]["roles"];
var result = from roleDetail in roles select new {Role=roleDetail["role"].AsBsonValue.ToString(),RoleDB=roleDetail["db"].AsBsonValue.ToString()};

这篇关于MongoDB C#驱动程序检查身份验证状态&amp;角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆