Search code examples
mongodbspring-bootdockerdocker-composeapplication.properties

Error authenticating MongoCredential when trying to connect from spring boot docker container to mongo docker container?


I have the following docker compose file, for a Spring boot container that connects to a mongoDB container:

#
# APIs
#----------------------------------------------
  pokerstats:
    image: pokerstats
    container_name: pokerstats
    ports:
      - 8080:8080
    depends_on: 
      - db

#
# Utilities
#----------------------------------------------
  db:
    image: mongo
    container_name: mongo
    volumes:
      - ./database:/data
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: admin
      MONGO_INITDB_DATABASE: pokerStats  

In my spring boot application.properties I have:

server.port=8080
spring.main.allow-bean-definition-overriding=true

spring.data.mongodb.uri=mongodb://admin:admin@mongo:27017/pokerStats
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=pokerStats

When I try to hit my endpoint using Postman I get the below error:

{
        "timestamp": "2020-04-07T17:39:19.129+0000",
        "status": 500,
        "error": "Internal Server Error",
        "message": "Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='admin', source='pokerStats', password=<hidden>, mechanismProperties=<hidden>}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='admin', source='pokerStats', password=<hidden>, mechanismProperties=<hidden>}",
        "path": "/rounds"
    }

Note that this was working fine before I added below to my docker compose file:

 environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: admin
      MONGO_INITDB_DATABASE: pokerStats  

Solution

  • I was able to resolve the issue by adding:

    application.properties:

    spring.data.mongodb.uri=mongodb://admin:admin@mongo:27017/pokerStats?authSource=admin
    spring.data.mongodb.authentication-database = admin
    spring.data.mongodb.database=pokerStats
    

    I believe that: ?authSource=admin needs added to end of the mongo uri.