Ciro Anacleto
Ciro Anacleto

Reputation: 119

Spring boot reactive and mongodb 'command insert requires authentication'

I created a project using Spring Boot 2.3.1 with webflux and MongoDB in a docker container. The project starts normally and connect in MongoDB with the params declared in application.properties.

The problem beggins when I try execute a CRUD operation "insert". The following log is generated:

500 Server Error for HTTP POST "/configuracao"

org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 13 (Unauthorized): 'command insert requires authentication' on server 127.0.0.1:27017. The full response is {"ok": 0.0, "errmsg": "command insert requires authentication", "code": 13, "codeName": "Unauthorized"}; nested exception is com.mongodb.MongoCommandException: Command failed with error 13 (Unauthorized): 'command insert requires authentication' on server 127.0.0.1:27017. The full response is {"ok": 0.0, "errmsg": "command insert requires authentication", "code": 13, "codeName": "Unauthorized"}
    at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:133) ~[spring-data-mongodb-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Assembly trace from producer [reactor.core.publisher.MonoError] :
    reactor.core.publisher.MonoFlatMapMany$FlatMapManyInner.onError(MonoFlatMapMany.java:247)
    com.mongodb.reactivestreams.client.internal.AbstractSubscription.onError(AbstractSubscription.java:139)
Error has been observed at the following site(s):
    |_ MonoFlatMapMany$FlatMapManyInner.onError ⇢ at com.mongodb.reactivestreams.client.internal.AbstractSubscription.onError(AbstractSubscription.java:139)
    |_                          Flux.onErrorMap ⇢ at org.springframework.data.mongodb.core.ReactiveMongoTemplate.createFlux(ReactiveMongoTemplate.java:651)
    |_                                Flux.last ⇢ at org.springframework.data.mongodb.core.ReactiveMongoTemplate.insertDocument(ReactiveMongoTemplate.java:1578)
    |_                                 Mono.map ⇢ at org.springframework.data.mongodb.core.ReactiveMongoTemplate.insertDocument(ReactiveMongoTemplate.java:1578)
    |_                             Mono.flatMap ⇢ at org.springframework.data.mongodb.core.ReactiveMongoTemplate.lambda$doInsert$35(ReactiveMongoTemplate.java:1344)
    |_                             Mono.flatMap ⇢ at org.springframework.data.mongodb.core.ReactiveMongoTemplate.doInsert(ReactiveMongoTemplate.java:1342)
    |_                                 Mono.map ⇢ at org.springframework.http.codec.json.AbstractJackson2Encoder.encode(AbstractJackson2Encoder.java:120)
    |_                                Mono.flux ⇢ at org.springframework.http.codec.json.AbstractJackson2Encoder.encode(AbstractJackson2Encoder.java:121)
    |_                       Flux.singleOrEmpty ⇢ at org.springframework.http.codec.EncoderHttpMessageWriter.write(EncoderHttpMessageWriter.java:121)
    |_                       Mono.switchIfEmpty ⇢ at org.springframework.http.codec.EncoderHttpMessageWriter.write(EncoderHttpMessageWriter.java:122)
    |_                             Mono.flatMap ⇢ at org.springframework.http.codec.EncoderHttpMessageWriter.write(EncoderHttpMessageWriter.java:126)
    |_                               checkpoint ⇢ Handler br.com.example.exampleapplication.controller.ConfiguracaoController#save(Configuracao) [DispatcherHandler]
    |_                             Mono.flatMap ⇢ at org.springframework.web.reactive.DispatcherHandler.lambda$handleResult$5(DispatcherHandler.java:172)
    |_                       Mono.onErrorResume ⇢ at org.springframework.web.reactive.DispatcherHandler.handleResult(DispatcherHandler.java:171)
    |_                             Mono.flatMap ⇢ at org.springframework.web.reactive.DispatcherHandler.handle(DispatcherHandler.java:147)
    |_                               Mono.defer ⇢ at org.springframework.web.server.handler.DefaultWebFilterChain.filter(DefaultWebFilterChain.java:119)
    |_                         Mono.doOnSuccess ⇢ at org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter.filter(MetricsWebFilter.java:78)
    |_                           Mono.doOnError ⇢ at org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter.filter(MetricsWebFilter.java:79)
    |_                   Mono.transformDeferred ⇢ at org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter.filter(MetricsWebFilter.java:73)
    |_                               checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
    |_                               Mono.defer ⇢ at org.springframework.web.server.handler.DefaultWebFilterChain.filter(DefaultWebFilterChain.java:119)
    |_                               Mono.error ⇢ at org.springframework.web.server.handler.ExceptionHandlingWebHandler$CheckpointInsertingHandler.handle(ExceptionHandlingWebHandler.java:98)
    |_                               checkpoint ⇢ HTTP POST "/configuracao" [ExceptionHandlingWebHandler]
    |_                       Mono.onErrorResume ⇢ at org.springframework.web.server.handler.ExceptionHandlingWebHandler.handle(ExceptionHandlingWebHandler.java:77)

Reading the Spring Data MongoDB Reference Documentation, I create a custom Bean for mongodb config as suggested:

@Configuration
@EnableTransactionManagement
@EnableReactiveMongoRepositories
public class MongoConfiguration extends AbstractReactiveMongoConfiguration {

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Bean
    public MongoClient mongoClient() {
        return MongoClients.create("mongodb://exampleapp:example@localhost:27017/exampledb");
    }

//    @Bean
//    public ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory() {
//        return new SimpleReactiveMongoDatabaseFactory(MongoClients.create("mongodb://exampleapp:example@localhost:27017/exampledb"), database);
//    }

    @Override
    protected String getDatabaseName() {
        return database;
    }

I tried with MongoClient and with ReactiveMongoDatabaseFactory and I can't execute the save method. Always is returned that 'command insert requires authentication'.

For the docker container I'm using this script to initialize the database after container startup:

db.auth('mongoadmin', 'mongoadmin')
db = db.getSiblingDB('exampledb')
db.createUser(
    {
        user: "exampleapp",
        pwd: "example",
        roles: [
            {
                role: "readWrite",
                db: "exampledb"
            }
        ]
    }
)

The application connects successfully on the startup, I can connect on the database using mongo-express or another gui tool.

What I doing wrong here? How I can configure this spring boot reactive app to propperly integrate with mongodb?

Thanks in advance.

Upvotes: 5

Views: 7589

Answers (1)

Amukelani
Amukelani

Reputation: 71

In case you are still having this issue. I had a similar problem and resolved it by using reactiveMongoClient() instead of mongoClient().

Replace:

 @Bean
public MongoClient mongoClient() {
    return MongoClients.create("mongodb://exampleapp:example@localhost:27017/exampledb");
}

With:

@Override
public MongoClient reactiveMongoClient() {
    return MongoClients.create("mongodb://exampleapp:example@localhost:27017/exampledb");
}

Your bean should look like:

@EnableReactiveMongoRepositories
@Slf4j
public class MongoDBCConfig extends 
AbstractReactiveMongoConfiguration {

@Override
protected String getDatabaseName() {
    return "dbname";
}

@Override
public MongoClient reactiveMongoClient() {
    return MongoClients.create("mongodb://username:password@localhost:27017/authSource=auth-source");
    }
}

Upvotes: 4

Related Questions