Search code examples
c#mongodbmongodb-.net-driver

MongoDB C# unable to connect to database: Unable to create an authenticator


While setting up my new environment with a freshly deployed MongoDB container with authentication enabled, I ran into this exception: "An unhandled exception has occurred while executing the request. MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.NotSupportedException: Unable to create an authenticator."

In my case I'm using a connection string like this example: mongodb://USER:PASSWORD@HOST:27017/?authMechanism=DEFAULT. This string works perfectly fine in MongoDB Compass but not inside my .NET 6.0 application.


Solution

  • If you take a look at the source code of C# MongoDB driver in MongoCredential.cs#L469, you see this exception gets thrown while checking the auth mechanism.

    After specifying the exact auth mechanism in the connection string, all exceptions are gone!

    example: mongodb://USER:PASSWORD@HOST:27017/?authMechanism=SCRAM-SHA-256

    Hope anyone else googeling around will find my answer helpful!

    happy coding.