I have following code to save to a local running mongo instance:
MongoCredential credential = MongoCredential.createCredential("myuser", "mydatabase", "mypassword".toCharArray());
MongoClient mongo = MongoClients.create(MongoClientSettings.builder()
.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new
ServerAddress("localhost", 27017))))
.credential(credential)
.build());
MongoDatabase database = mongo.getDatabase("mydatabase");
MongoCollection<Document> collection = database.getCollection("mycollection");
collection.insertOne(document);
I have created a user for usernmae/password used in code above using db.createUser() command in mongo.exe shell and these are same credentials I provided while installing mongodb.
db.createUser(
{ user: "myuser",
pwd: "mypassword",
roles:[{role: "userAdminAnyDatabase" , db:"admin"}]})
But code fails with:
Exception in thread "main" com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='myuser', source='mydatabase', password=<hidden>, mechanismProperties={}}
What am I missing here?