MongoDB C#驱动程序检查身份验证状态和角色

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

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).这不是检查登录状态的好方法.

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

解决方法:

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

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

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

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()};
上一篇:javascript-从bookmarklet检查身份验证


下一篇:我国常用的坐标系统WKID列表[转]