Search code examples
c#mongodbmongodb-.net-drivermongodb-csharp-2.0

Password Special Charecter issue in mongoDB?


Error : Password Special Character issue in mongoDB

Code:

connstr="mongodb://test:test@123@67.186.193.192:27017/testdb"

Here i changed password "test@123" to "test%4123" . Because @ ASCII code is %4 Now it is working fine.

MongoClient client = new MongoClient(connstr); //vss
var server = client.GetServer();

//server.Ping();
var db = client.GetDatabase(dbname);
List<KeyValuePair<string, string>> collections = new List<KeyValuePair<string, string>>();
var tableviewset = JArray.Parse(db.ListCollectionsAsync().Result.ToListAsync<BsonDocument>().Result.ToJson());

But my users will use different passwords like $,^,*,( ... etc. So in this situation what i do ?


Solution

  • You can do somthing like this , you can user MongoClientSettings for password and all other parameter.

     private MongoClientSettings GetSecuritySettingForConnection()
            {
                MongoClientSettings settings = new MongoClientSettings();
                settings.Server = new MongoServerAddress(host, port);
                MongoIdentity identity = new MongoInternalIdentity(authenticationDatabase, userName);
                MongoIdentityEvidence evidence = new PasswordEvidence(password);
                settings.Credentials = new List<MongoCredential>()
                {
                    new MongoCredential("SCRAM-SHA-1", identity, evidence)
    
                };
                settings.MaxConnectionIdleTime = new TimeSpan(0, 2, 0);
                return settings;
            }
    

    After that You can this function over here:

     var client = new MongoClient(GetSecuritySettingForConnection());
    

    Let me know if any confusion.