3

I have the following working configurations in my Spring application:

<mongo:mongo id="myRs" replica-set="myhost:27017">

  <mongo:options max-wait-time="1500"
                   connect-timeout="30000" />
</mongo:mongo>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <property name="writeResultChecking" value="EXCEPTION"/>
    <property name="writeConcern" value="FSYNC_SAFE"/>
    <constructor-arg ref="myRs"/>
    <constructor-arg name="databaseName" value="mydb"/>
</bean>

Now all I want to do is to set up username/password for accessing the mongo database without changing my code (i.e. only by updating the Spring app context xml file). Is that possible? If so, how?

Thanks.

1 Answer 1

6

You can pass username password like this to MongoTemplate. Using PropertyPlaceholderConfigurer you can even read the username and password from a property file.

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <property name="writeResultChecking" value="EXCEPTION"/>
    <property name="writeConcern" value="FSYNC_SAFE"/>
    <constructor-arg ref="myRs"/>
    <constructor-arg name="databaseName" value="mydb"/>
    <constructor-arg name="userCredentials" ref="userCredentials"/>
</bean>

<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
    <constructor-arg name="username" value="username" />
    <constructor-arg name="password" value="password" />
</bean>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Now I have to set up the users on the DB side. I have replica sets for each environment. Do I need to manually add the credentials to each mongo master using mongo shell? Is there a better way?
Does the above UserCredentials bean work with replica sets? It seems there is no username/password choice for replica sets? (at least for MongoDb 2.2) docs.mongodb.org/v2.2/administration/replica-sets/…
I have not played with replica sets so not sure how that can be done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.