Skip to content

MongoClient autoconfiguration does not take into account authentication-database property #2562

@chli1

Description

@chli1

I have set username, password and authentication-database properties set in my configuration file as follows:

spring.data.mongodb.database=customdata
spring.data.mongodb.username=top
spring.data.mongodb.password=secret
spring.data.mongodb.authentication-database=admin

Then I'm using the default autoconfiguration to create a MongoClient object and passing it to mongeez. But I did not manage to do a successful authentication. Stepping through the code and looking into the server logs, I saw that mongo client still tries to authenticate using the database "customdata" instead of "admin".

I think the problem is within the method MongoProperties.createMongoClient(MongoClientOptions) that creates a new MongoClient.

The client is configured to use credentials from its properties object, but it does not use the authenticationDatabase proptery. Instead it uses the configured database property when creating the Credentials object.

See:

credentials = Arrays.asList(MongoCredential.createMongoCRCredential(
    this.username, getMongoClientDatabase(), this.password));

I would expect here that getAuthenticationDatabase() is used instead of getMongoClientDatabase(), if available.

As a work-around I'm currently implementing the createMongoClient by myself and creating credentials using the authentication database, see:

@Autowired
private MongoProperties properties;

@Bean
public Mongo mongo() throws UnknownHostException {
    List<MongoCredential> credentials = null;
    if (properties.getUsername() != null || properties.getPassword() != null) {
        credentials = Arrays.asList(MongoCredential.createMongoCRCredential(
                properties.getUsername(), properties.getAuthenticationDatabase(), properties.getPassword()));
    }
    String host = properties.getHost() == null ? "localhost" : properties.getHost();
    int port = properties.getPort() == null ? 27017 : properties.getPort();
    return new MongoClient(Arrays.asList(new ServerAddress(host, port)),
            credentials, options);
}

That solves the problem for me but, it's a rather special solution, I think the client database property should be used as fall-back if authentication database property is not set, but if it is set, I would expect that it is used here.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions