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:
Define users:
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:
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?To connect: MongoClient client = MongoClients. create("<<MongoDB URI>>"); To connect to MongoDB on your local instance and default port, you can just omit the URI part of the above, or use a URI like 'mongodb://localhost:27017'.
MongoDB users can use usernames and passwords to authenticate themselves against a MongoDB database.
Tested with mongodb-3.4.2 and mongo-java-driver-3.4.2.jar
(1) Use MongoCredential
MongoCredential credential = MongoCredential.createCredential("user", "database", "passwd".toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(credential));
MongoDatabase db = mongoClient.getDatabase( "test" );
MongoCollection collection = db.getCollection("mycol");
FindIterable fi = collection.find();
MongoCursor cursor = fi.iterator();
(2) Use MongoClientURI
MongoClientURI uri = new MongoClientURI("mongodb://user:passwd@localhost:27017/?authSource=test");
MongoClient mongoClient = new MongoClient(uri);
There are some variant forms for using MongoCredential and MongoClientURI for different authentication mechanisms, check here for details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With