java 连接到MongoDB时出现Sping Boot 身份验证错误

lvjbypge  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(175)

我使用docker-compose运行MongoDB和mongodb-express,我试图从Sping Boot 构建一个可以与MongoDB对话的REST API,但是Spring Boot应用程序在尝试连接到MongoDB时无法启动。
docker-compose.yaml

version: "3.8"
    
services:
    
  mongodb:
    image: mongo
    container_name: mongodb
    ports:
      - "27017:27017"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=rootuser
      - MONGO_INITDB_ROOT_PASSWORD=rootpass
    
  mongo-express:
    image: mongo-express
    container_name: mongo-express
    ports:
      - "8081:8081"
    restart: always
    environment:
      - ME_CONFIG_MONGODB_ADMINUSERNAME=rootuser
      - ME_CONFIG_MONGODB_ADMINPASSWORD=rootpass
      - ME_CONFIG_MONGODB_SERVER=mongodb
    
networks:
  default:
    name: mongodb-network

application.properties

spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=rootuser
spring.data.mongodb.password=rootpass
spring.data.mongodb.database=mymongodb
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
logging.level.org.springframework.web=DEBUG


        
    PS C:\Users\utkar\Documents\SpringBoot2022\mongodb-crud-tutorial> docker compose ps
    NAME                COMMAND                  SERVICE             STATUS              PORTS
    mongo-express       "tini -- /docker-ent…"   mongo-express       running             0.0.0.0:8081->8081/tcp
    mongodb             "docker-entrypoint.s…"   mongodb             running             0.0.0.0:27017->27017/tcp

启动spring Boot 项目时出错

:: Spring Boot ::                (v2.7.3)

    2022-09-19 23:00:01.187  INFO 103344 --- [           main] c.a.c.m.MongodbCrudTutorialApplication   : Starting MongodbCrudTutorialApplication using Java 17.0.2 on DESKTOP-R90T7LM with PID 103344 (C:\Users\utkar\Documents\SpringBoot2022\mongodb-crud-tutorial\target\classes started by utkar in C:\Users\utkar\Documents\SpringBoot2022\mongodb-crud-tutorial)
    2022-09-19 23:00:01.190  INFO 103344 --- [           main] c.a.c.m.MongodbCrudTutorialApplication   : No active profile set, falling back to 1 default profile: "default"
    2022-09-19 23:00:02.048  INFO 103344 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
    2022-09-19 23:00:02.095  INFO 103344 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 41 ms. Found 1 MongoDB repository interfaces.
    2022-09-19 23:00:12.121  INFO 103344 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2022-09-19 23:00:12.133  INFO 103344 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2022-09-19 23:00:12.134  INFO 103344 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.65]
    2022-09-19 23:00:12.618  INFO 103344 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2022-09-19 23:00:12.618  INFO 103344 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 11375 ms
    2022-09-19 23:00:12.862  INFO 103344 --- [           main] org.mongodb.driver.client                : MongoClient with metadata {"driver": {"name": "mongo-java-driver|sync|spring-boot", "version": "4.6.1"}, "os": {"type": "Windows", "name": "Windows 10", "architecture": "amd64", "version": "10.0"}, "platform": "Java/Eclipse Adoptium/17.0.2+8"} created with settings MongoClientSettings{readPreference=primary, writeConcern=WriteConcern{w=null, wTimeout=null ms, journal=null}, retryWrites=true, retryReads=true, readConcern=ReadConcern{level=null}, credential=MongoCredential{mechanism=null, userName='rootuser', source='admin', password=<hidden>, mechanismProperties=<hidden>}, streamFactoryFactory=null, commandListeners=[], codecRegistry=ProvidersCodecRegistry{codecProviders=[ValueCodecProvider{}, BsonValueCodecProvider{}, DBRefCodecProvider{}, DBObjectCodecProvider{}, DocumentCodecProvider{}, IterableCodecProvider{}, MapCodecProvider{}, GeoJsonCodecProvider{}, GridFSFileCodecProvider{}, Jsr310CodecProvider{}, JsonObjectCodecProvider{}, BsonCodecProvider{}, EnumCodecProvider{}, com.mongodb.Jep395RecordCodecProvider@542f6803]}, clusterSettings={hosts=[localhost:27017], srvServiceName=mongodb, mode=SINGLE, requiredClusterType=UNKNOWN, requiredReplicaSetName='null', serverSelector='null', clusterListeners='[]', serverSelectionTimeout='30000 ms', localThreshold='30000 ms'}, socketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=0, receiveBufferSize=0, sendBufferSize=0}, heartbeatSocketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=10000, receiveBufferSize=0, sendBufferSize=0}, connectionPoolSettings=ConnectionPoolSettings{maxSize=100, minSize=0, maxWaitTimeMS=120000, maxConnectionLifeTimeMS=0, maxConnectionIdleTimeMS=0, maintenanceInitialDelayMS=0, maintenanceFrequencyMS=60000, connectionPoolListeners=[], maxConnecting=2}, serverSettings=ServerSettings{heartbeatFrequencyMS=10000, minHeartbeatFrequencyMS=500, serverListeners='[]', serverMonitorListeners='[]'}, sslSettings=SslSettings{enabled=false, invalidHostNameAllowed=false, context=null}, applicationName='null', compressorList=[], uuidRepresentation=JAVA_LEGACY, serverApi=null, autoEncryptionSettings=null, contextProvider=null}
    2022-09-19 23:00:13.253  INFO 103344 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:43}] to localhost:27017
    2022-09-19 23:00:13.260  INFO 103344 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:42}] to localhost:27017
    2022-09-19 23:00:13.260  INFO 103344 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=17, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=376157600}
    2022-09-19 23:00:13.432 DEBUG 103344 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 @ModelAttribute, 0 @InitBinder, 1 RequestBodyAdvice, 1 ResponseBodyAdvice
    2022-09-19 23:00:13.553 DEBUG 103344 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : 2 mappings in 'requestMappingHandlerMapping'
    2022-09-19 23:00:13.577 DEBUG 103344 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
    2022-09-19 23:00:13.587 DEBUG 103344 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 @ExceptionHandler, 1 ResponseBodyAdvice
    2022-09-19 23:00:14.032  INFO 103344 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
    2022-09-19 23:00:14.039  INFO 103344 --- [           main] c.a.c.m.MongodbCrudTutorialApplication   : Started MongodbCrudTutorialApplication in 13.803 seconds (JVM running for 17.433)
    going to insert
    2022-09-19 23:00:14.356  INFO 103344 --- [           main] ConditionEvaluationReportLoggingListener : 
    
    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2022-09-19 23:00:14.390 ERROR 103344 --- [           main] o.s.boot.SpringApplication               : Application run failed
    
    java.lang.IllegalStateException: Failed to execute CommandLineRunner
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:774) ~[spring-boot-2.7.3.jar:2.7.3]
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:755) ~[spring-boot-2.7.3.jar:2.7.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.7.3.jar:2.7.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.3.jar:2.7.3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.3.jar:2.7.3]
        at com.amigos.code.mongodbcrudtutorial.MongodbCrudTutorialApplication.main(MongodbCrudTutorialApplication.java:16) ~[classes/:na]
    Caused by: org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='rootuser', source='admin', password=<hidden>, mechanismProperties=<hidden>}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='rootuser', source='admin', password=<hidden>, mechanismProperties=<hidden>}
        at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:140) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:3044) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:600) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        at org.springframework.data.mongodb.core.MongoTemplate.insertDocument(MongoTemplate.java:1546) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        at org.springframework.data.mongodb.core.MongoTemplate.doInsert(MongoTemplate.java:1345) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:1260) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.insert(SimpleMongoRepository.java:286) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
        at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:530) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:286) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:640) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.22.jar:5.3.22]
        at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:164) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:139) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.22.jar:5.3.22]
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:81) ~[spring-data-commons-2.7.2.jar:2.7.2]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.22.jar:5.3.22]
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.22.jar:5.3.22]
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.22.jar:5.3.22]
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.22.jar:5.3.22]
        at jdk.proxy2/jdk.proxy2.$Proxy55.insert(Unknown Source) ~[na:na]
        at com.amigos.code.mongodbcrudtutorial.MongodbCrudTutorialApplication.lambda$0(MongodbCrudTutorialApplication.java:34) ~[classes/:na]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:771) ~[spring-boot-2.7.3.jar:2.7.3]
        ... 5 common frames omitted
    Caused by: com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='rootuser', source='admin', password=<hidden>, mechanismProperties=<hidden>}
        at com.mongodb.internal.connection.SaslAuthenticator.wrapException(SaslAuthenticator.java:276) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.SaslAuthenticator.getNextSaslResponse(SaslAuthenticator.java:139) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.SaslAuthenticator.access$100(SaslAuthenticator.java:49) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:65) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:59) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:283) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:59) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:57) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.InternalStreamConnectionInitializer.authenticate(InternalStreamConnectionInitializer.java:207) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.InternalStreamConnectionInitializer.finishHandshake(InternalStreamConnectionInitializer.java:81) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:185) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:54) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:535) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.DefaultConnectionPool$OpenConcurrencyLimiter.openWithConcurrencyLimit(DefaultConnectionPool.java:911) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.DefaultConnectionPool$OpenConcurrencyLimiter.openOrGetAvailable(DefaultConnectionPool.java:852) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:178) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:167) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.DefaultServer.getConnection(DefaultServer.java:103) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:175) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.client.internal.ClientSessionBinding$SessionBindingConnectionSource.getConnection(ClientSessionBinding.java:192) ~[mongodb-driver-sync-4.6.1.jar:na]
        at com.mongodb.internal.operation.OperationHelper.withSuppliedResource(OperationHelper.java:592) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.operation.OperationHelper.lambda$withSourceAndConnection$3(OperationHelper.java:574) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.operation.OperationHelper.withSuppliedResource(OperationHelper.java:600) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.operation.OperationHelper.withSourceAndConnection(OperationHelper.java:573) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.operation.MixedBulkWriteOperation.lambda$execute$3(MixedBulkWriteOperation.java:272) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.async.function.RetryingSyncSupplier.get(RetryingSyncSupplier.java:65) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:308) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:85) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:212) ~[mongodb-driver-sync-4.6.1.jar:na]
        at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1010) ~[mongodb-driver-sync-4.6.1.jar:na]
        at com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:471) ~[mongodb-driver-sync-4.6.1.jar:na]
        at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:454) ~[mongodb-driver-sync-4.6.1.jar:na]
        at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:448) ~[mongodb-driver-sync-4.6.1.jar:na]
        at org.springframework.data.mongodb.core.MongoTemplate.lambda$insertDocument$15(MongoTemplate.java:1552) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:598) ~[spring-data-mongodb-3.4.2.jar:3.4.2]
        ... 31 common frames omitted
    Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}
        at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:198) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:413) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:337) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:101) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:45) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:230) ~[mongodb-driver-core-4.6.1.jar:na]
        at com.mongodb.internal.connection.SaslAuthenticator.getNextSaslResponse(SaslAuthenticator.java:137) ~[mongodb-driver-core-4.6.1.jar:na]
        ... 64 common frames omitted
k5ifujac

k5ifujac1#

你能测试一下吗,替换:

spring.data.mongodb.authentication-database=admin  
spring.data.mongodb.username=rootuser  
spring.data.mongodb.password=rootpass  
spring.data.mongodb.database=mymongodb  
spring.data.mongodb.port=27017  
spring.data.mongodb.host=localhost

通过

spring.data.mongodb.uri=mongodb://rootuser:rootpass@localhost:27017  
spring.data.mongodb.database=mymongodb

在您的文件application.properties

相关问题