问题
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?
回答1:
Where, i.e. in which database did you create the user? Typically users are created in database admin. When you connect to a MongoDB then you should always specify the authentication database and the database you like to use.
The defaults are a bit confusing, see this table to get an overview:
+---------------------------------------------------------------------------------------------+
|Connection string | Authentication DB | Current DB |
+---------------------------------------------------------------------------------------------+
|mongo -u <...> -p <...> --authenticationDatabase admin myDB | admin | myDB |
|mongo -u <...> -p <...> myDB | myDB | myDB |
|mongo -u <...> -p <...> --authenticationDatabase admin | admin | test |
|mongo -u <...> -p <...> | admin | test |
+---------------------------------------------------------------------------------------------+
If you like to use Connection string in URI format, it would correspond to these ones:
mongodb://<username>:<password>@hostname/myDB?authSource=admin
mongodb://<username>:<password>@hostname/myDB
mongodb://<username>:<password>@hostname?authSource=admin
mongodb://<username>:<password>@hostname
I guess you created the user in admin database but as you don't specify authenticationDatabase while connecting, Mongo defaults it to mydatabase where it fails, because user does not exist in database mydatabase.
来源:https://stackoverflow.com/questions/63754742/authentication-failure-while-trying-to-save-to-mongodb