简体   繁体   English

Spring 启动反应和 mongodb '命令插入需要身份验证'

[英]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.我在 docker 容器中使用带有 webflux 和 MongoDB 的 Spring Boot 2.3.1 创建了一个项目。 The project starts normally and connect in MongoDB with the params declared in application.properties .项目正常启动并在 MongoDB 与application.properties中声明的参数连接。

The problem beggins when I try execute a CRUD operation "insert".当我尝试执行 CRUD 操作“插入”时,问题就开始了。 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:阅读Spring 数据 MongoDB 参考文档,我按照建议为 mongodb 配置创建了一个自定义 Bean:

@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.我尝试了MongoClientReactiveMongoDatabaseFactory ,但我无法执行save方法。 Always is returned that 'command insert requires authentication' .总是返回'command insert requires authentication'

For the docker container I'm using this script to initialize the database after container startup:对于 docker 容器,我使用此脚本在容器启动后初始化数据库:

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.应用程序在启动时连接成功,我可以使用 mongo-express 或其他 gui 工具连接数据库。

What I doing wrong here?我在这里做错了什么? How I can configure this spring boot reactive app to propperly integrate with mongodb?如何配置此 spring 启动反应式应用程序以正确集成 mongodb?

Thanks in advance.提前致谢。

In case you are still having this issue.如果您仍然遇到此问题。 I had a similar problem and resolved it by using reactiveMongoClient() instead of mongoClient().我有一个类似的问题,并通过使用 reactiveMongoClient() 而不是 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:您的 bean 应如下所示:

@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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WebFlux Spring Boot @Transactional 与反应式 MongoDB - WebFlux Spring Boot @Transactional with reactive MongoDB 审核(@CreatedDate)不适用于带有反应式 MongoDB 的 WebFlux Spring Boot - Auditing (@CreatedDate) does not work for WebFlux Spring Boot with reactive MongoDB 为什么 Spring-boot 应用程序需要 CommandLineRunner 插入新记录? - Why the Spring-boot application requires CommandLineRunner to insert new records? 在Maven中看不到spring-boot-starter-data-mongodb-active和spring-boot-starter-webflux依赖性 - Dont see spring-boot-starter-data-mongodb-reactive and spring-boot-starter-webflux dependency in maven 更新 1 个或多个特定字段 MongoDB 使用 Spring 启动 WebFlux,Spring 数据 Z206E3718AF0921CC1D12F80ZReposit7 - Update 1 or multiple specific field MongoDB using Spring boot WebFlux,Spring Data MongoDB Reactive and ReactiveMongoRepository 通过 Spring Boot 应用程序访问 mongodb 时出现身份验证错误 - Authentication error when accessing mongodb through Spring Boot app Spring Boot Webflux 反应式 API - Spring Boot Webflux reactive api 使用 MySql 启动响应式 Spring (Webflux) - Spring boot reactive (Webflux) with MySql Spring Boot 反应式 redis 连接 - Spring boot reactive redis connection 使用Spring Boot在MongoDB中对JSON对象进行插入和获取操作 - Insert and Get operations on JSON object in MongoDB with Spring Boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM