Authentication error when database is in connection string

When I create a MongoUrl like this:

MongoUrl url = new MongoUrl("mongodb://mongoadmin:secret@localhost:27019/Testing");

I can access the DatabaseName property without any issues.

However, when I use the following code to create a client:

var url = new MongoUrl("mongodb://mongoadmin:secret@localhost:27019/Testing");
var client = new MongoClient(url);
var database = client.GetDatabase(url.DatabaseName);

and try to list collections, I encounter the following authentication error:

Unhandled exception. MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1.

Interestingly, if I remove the database name from the connection string:

var url = new MongoUrl("mongodb://mongoadmin:secret@localhost:27019");

the authentication error does not occur.

It’s strange that I can access the DatabaseName property from the MongoUrl, but including the database name in the connection string results in an authentication error when creating and connecting to the client.

Hey @William_N_A2 , this is expected behavior, as the driver is trying to use the database you provided as the authentication source.

If you’re using the default authentication database (admin), then connecting as follows should work: mongodb://mongoadmin:secret@localhost:27019/Testing?authSorce=admin

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.