Search code examples
javamongodbspring-bootspring-data-mongodbreplicaset

Mongodb replicaset authetication failing from spring boot


I have 3 instance mongodb replicaset including 1 arbiter in 3 different ec2 instance. From mongo console I am able to connect to replica set. But when I try to build/deploy my dockerized spring boot apllication in the primary ec2 instance it gives below exception

Caused by: org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='<usrName>', source='<source>', password=<hidden>, mechanismProperties=<hidden>}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='<usrName>', source='<source>', password=<hidden>, mechanismProperties=<hidden>}
Caused by: com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='<usrName>', source='<source>', password=<hidden>, mechanismProperties=<hidden>}
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server <Primary-Host>:27017. The full response is {"operationTime": {"$timestamp": {"t": 1601217500, "i": 1}}, "ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed", "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1601217500, "i": 1}}, "signature": {"hash": {"$binary": {"base64": "KSwBAZHnhcqmjdsAy9HHVB8+yZQ=", "subType": "00"}}, "keyId": 6876114453302083588}}}

Spring data mongodb properties used while connecting to replicaset

spring.data.mongodb.uri=mongodb://<usrName>:<password>@<host-primary>:27017,<host-secondary>:27017/<dbName>?<replicaset name>
spring.data.mongodb.auto-index-creation = true

Where as when I try to build/deploy using below properties i.e single node connection this is getting successfull

spring.data.mongodb.host=<Primary-Host>
spring.data.mongodb.port=27017
spring.data.mongodb.database=<database name>
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=<user name>
spring.data.mongodb.password=<password>
spring.data.mongodb.auto-index-creation = true

Solution

  • Does username or password contains at sign @, colon :, slash /, or the percent sign % character ?

    If yes check if you are using correct encoding.

    Also try adding authSource in uri like so :

    ?authSource=admin&replicaSet=myRepl