Hi, After migration from Spring boot 3.0.6 to 3.1.0, the application using proproty authenticationDatabase can not authenticate against MongoDB.

Following exception:

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:205) ~[mongodb-driver-core-4.9.1.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:443) ~[mongodb-driver-core-4.9.1.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:365) ~[mongodb-driver-core-4.9.1.jar:na]
    at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:102) ~[mongodb-driver-core-4.9.1.jar:na]
    at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:49) ~[mongodb-driver-core-4.9.1.jar:na]
    at com.mongodb.internal.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:224) ~[mongodb-driver-core-4.9.1.jar:na]
    at com.mongodb.internal.connection.SaslAuthenticator.getNextSaslResponse(SaslAuthenticator.java:131) ~[mongodb-driver-core-4.9.1.jar:na]
    ... 80 common frames omitted

After digging into the code, I found out the root cause is coming from the newly introduced PropertiesMongoConnectionDetails.java, which ignores the authenticationDatabase once a client database configured. The related code of building the mongodb connection uri.:

if (this.properties.getMongoClientDatabase() != null || this.properties.getReplicaSetName() != null
                || this.properties.getAuthenticationDatabase() != null) {
            builder.append("/");
            if (this.properties.getMongoClientDatabase() != null) {
                builder.append(this.properties.getMongoClientDatabase());
            }
            **else** if (this.properties.getAuthenticationDatabase() != null) {
                builder.append(this.properties.getAuthenticationDatabase());
            }
            if (this.properties.getReplicaSetName() != null) {
                builder.append("?");
                builder.append("replicaSet=");
                builder.append(this.properties.getReplicaSetName());
            }
        }

Comment From: wilkinsona

Duplicates https://github.com/spring-projects/spring-boot/issues/35567.