MongoDB C#驱动程序检查身份验证状态和角色(MongoDB C# Driver check Authentication status & Role)

编程入门 行业动态 更新时间:2024-10-23 09:29:15
MongoDB C#驱动程序检查身份验证状态和角色(MongoDB C# Driver check Authentication status & Role)

这是我使用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) { }

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

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

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) { }

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服务器上执行某个a时才会抛出异常。 但是,正如您所发现的那样,该异常是一个通用的超时异常,表明驱动程序无法找到合适的服务器。 由于异常本身确实包含有关失败的详细信息,因此您可以使用该信息创建类似下面的方法,以检查是否可以对数据库运行伪命令。 在这种方法中,我将所有超时值减少到一秒:

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

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

更多推荐

本文发布于:2023-07-25 05:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1256748.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:驱动程序   身份验证   角色   状态   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!