I'm using MongoDB 3.2 in my application. The code below demonstrates database initialization logic:
private void dbInit(String dbName) {
String mongoClientURI = "mongodb://" + DB_URL + ":" + DB_PORT;
MongoClientURI connectionString = new MongoClientURI(mongoClientURI);
// enable SSL connection
MongoClientOptions.builder().sslEnabled(true).build();
if (this.mongoClient == null) {
this.mongoClient = new MongoClient(connectionString);
}
// create database if doesn't exist
this.mongoClient.getDatabase(dbName);
}
This code works fine, now I want to introduce access level separation to database.
The steps to do that:
use myAppDB
db.createUser(
{
"user": "myAdmin",
"pwd": "123090d1487dd4ab7",
roles: [ "readWrite", "dbAdmin" ]
}
)
use myAppDB
db.createUser(
{
"user": "guest",
"pwd": "guest",
roles: [ "read" ]
}
)
Re-create the MongoDB 3.2 service in authentication mode:
"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe" --install --dbpath=C:\data\db --logpath=C:\data\log\log.txt --auth --service
. And run it.
Change the mongoClientURI
connection string to
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT;
where DB_SRV_USR
= myAdmin
and DB_SRV_PWD
= 123090d1487dd4ab7
.
Check the authenticated connection in IDEA's Mongo Explorer
with the same credentials, everything is OK.
Execute my application and get exception Authentication failed
.
My questions:
How to connect to MongoDB 3.2 in Java with username and password? I saw a couple of examples but they are using deprecated methods.
Should I add my users to myAppDB
or to admin
table? In some tutorials I saw that users are created in admin
table is it a good idea or it worth to create users only in a database they are going to work with?
As MarkusWMahlberg correctly noted, it is necessary to note the database name in the connection string.
For instance:
String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT + "/" + dbName;