Search code examples
mongodb.net-corehangfire

Hangfire MongoDB .Net Core Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1


I am using .Net Core 3.1 and Hangfire MongoDb for background scheduling, now on startup it is throwing

Autofac.Core.DependencyResolutionException: An exception was thrown while activating λ:Hangfire.IGlobalConfiguration.
 ---> MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1.
 ---> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed..
   at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)
   at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)
   at MongoDB.Driver.Core.Authentication.SaslAuthenticator.Authenticate(IConnection connection, ConnectionDescription description, CancellationToken cancellationToken

My Connection string in the config file is correct and I am able to connect to the DB from the same connection string through the Mongo Client

"ConnectionStrings": {
"MongoJobSchedulerConnection": "mongodb://user:password@ipaddress:port/DbName"
}

This is how I am adding Hangfire in Startup.cs

var mongoUrlBuilder = new MongoUrlBuilder(configuration.GetConnectionString("MongoJobSchedulerConnection"));
            var mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
            

            services.AddHangfire((sp,configuration) => configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseActivator<JobActivator>(new SchedulerJobActivator(sp.GetRequiredService<IServiceScopeFactory>()))
                .UseMongoStorage(mongoClient, mongoUrlBuilder.DatabaseName, new MongoStorageOptions
                {
                    MigrationOptions = new MongoMigrationOptions
                    {
                        MigrationStrategy = new MigrateMongoMigrationStrategy(),
                        BackupStrategy = new CollectionMongoBackupStrategy()
                    },
                    Prefix = "SchedulerQueue",
                    CheckConnection = true
                })
            );

any hint on the issue will be a great help

Thank You


Solution

  • The reason for this was MongoDB authentication was not happening against the admin DB somehow This can be fixed by adding auth source to connection string like

    "ConnectionStrings": {
    "MongoJobSchedulerConnection": "mongodb://user:password@ipaddress:port/DbName?authSource=admin"
    }
    

    or this can be specified in MongoUrlBuilder like

    var mongoUrlBuilder = new MongoUrlBuilder(configuration.GetConnectionString("MongoJobSchedulerConnection"));
    mongoUrlBuilder.AuthenticationSource = "admin";