Akshay Som
Akshay Som

Reputation: 31

Spring data-MongoDb Manual configuration

What I finally want to achieve is, connect to mongo db from java class, this configuration should be applicable to both MongoTemplate and MongoRepository

spring boot provides configuration of mongodb directly via application.properties file by below properties

spring.data.mongodb.database=delivery
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.password=delivery-user
spring.data.mongodb.username=delivery-user

Instead of this way , I need to connect to db with java class itself, This is because I need to make the password encrypted in properties file and then decrypt from java class from my understanding I have tried creating a class below

@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {

    @Override
    public MongoClient mongoClient() {
        String username = "delivery-user";
        String password = "delivery-user";
        String port = "27017";
        String host = "localhost";
        String db = "salesdata";
//have also tried by passing db name in conString
        String conString = "mongodb://" + username + ":" + password + "@" + host + ":" + port+"/?authSource=admin" ;
        MongoClient mClient = MongoClients.create(conString);
        return mClient;

    }

    @Override
    protected String getDatabaseName() {
        return "delivery";
    }

    @Bean
    @Override
    public MongoTemplate mongoTemplate() {
        MongoTemplate mt = new MongoTemplate(mongoClient(), getDatabaseName());
        return mt;
    }
}

Im getting this error when running this application

 Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='delivery-user', source='admin', password=<hidden>, mechanismProperties={}}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='delivery-user', source='admin', password=<hidden>, mechanismProperties={}}

The username and password is correct, also user has access to "delivery" db

Upvotes: 2

Views: 5777

Answers (1)

Akshay Som
Akshay Som

Reputation: 31

Specifying db name in end of string and removing "authSource" will solved the problem. Also specifying "authSource=targetDBname" seems to be working. example for working connection string

String conString = "mongodb://" + username + ":" + password + "@" + host + ":" + port+"/dbName";

Replace dbName with name of db in which the user has access to.

Upvotes: 1

Related Questions