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

这是我使用MongoDB身份validation机制登录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("book"); var filter = new BsonDocument(); var document = collection.Find(new BsonDocument()).ToList(); } catch (Exception ex) { } 

当我们在Credential中输入错误的用户名/密码时,如何检查登录结果? 目前我无法检查它,我必须等待collection.Find().ToList()抛出一个TimeoutException ,并在此上下文中它的身份validation失败。 我们必须创建一个CRUD来检查身份validation结果(通过捕获TimeoutException )。 检查登录状态不是一个好方法。

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

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

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