Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB C# Driver MongoCredential object

The documentation for the MongoDB Driver seems to differ from the actual driver pulled from NuGet.

More specifically, the documented "MongoCredentials" (plural) doesn’t exist, but only "MongoCredential" (singular). Further, MongoServer.GetDatabase doesn't seem to have a constructor that accepts MongoCredential, only MongoDatabaseSettings (alongside a string that names the databae), and I see no apparent way of giving a MongoDatabaseSettings object a MongoCredential object.

I haven't found any examples on Google with the objects I'm finding in the driver, only ones that align with the (outdated?) official documentation.

The driver that I'm using is called (in the NuGet Package Manager) "Official MongoDB C# driver."

To summarize: How does one actually provide credentials in the C# driver?

like image 318
Ranger Avatar asked Mar 21 '23 22:03

Ranger


1 Answers

I'm also using the Official MongoDB C# driver from NuGet, version 1.8.3.

Indeed, the CSharp Driver Tutorial seems outdated.

However, the API documentation is correct; there's an entry there for the MongoCredential class (singular).

You can create a credential using either the constructor or one of the static factory methods (CreateGssapiCredential or CreateMongoCRCredential).

Next, in order to use the credentials you cannot specify them in the GetDatabase() call, but earlier, when you create the Server, like so:

var db1Credential = MongoCredential.CreateMongoCRCredential("db1", "uid", "pwd");
var db2Credential = MongoCredential.CreateMongoCRCredential("db2", "uid", "pwd");

var server = new MongoServer(
    new MongoServerSettings
        {
            Server = new MongoServerAddress("localhost", 27017),
            Credentials = new[]
                            {
                                db1Credential,
                                db2Credential
                            }
        });
like image 72
Cristian Lupascu Avatar answered Apr 01 '23 13:04

Cristian Lupascu