所以出于某种奇怪的原因,我的用户没有被授权在krimson数据库中写入任何东西。数据库连接成功,但授予用户写入数据库的权限未按预期工作。
完全错误
Caused by: com.mongodb.MongoCommandException: Command failed with error 13: 'not authorized on krimson to execute command { findandmodify: "users", query: { _id: "_id" }, fields: {}, sort: {}, new: true, upsert: true, update: { $i
nc: { _id: 1 } } }' on server ds037395.mongolab.com:37395. The full response is { "ok" : 0.0, "errmsg" : "not authorized on krimson to execute command { findandmodify: "users", query: { _id: "_id" }, fields: {}, sort: {}, new:
true, upsert: true, update: { $inc: { _id: 1 } } }", "code" : 13 }
连接代码
public static void connects(String ip, int port, String database, String username, String password) {
try {
client = new MongoClient(ip, port); /**Creating our connection between server & MongoDB*/
krimson = client.getDB(database); /**Checks if the database exists or not if not then create a new one*/
MongoCredential.createCredential(username, database, password.toCharArray()); /**Credentials used to connect to MongoDB*/
} catch (Exception e){
e.printStackTrace();
System.out.println("Linking connections failed"); /**Outputs when the database cannot connect*/
UtilServer.broadcast("&c&lThe Krimson Library did not establish a successfully connection.");
}
users = krimson.getCollection("users");
}
我试图在凭据中重新创建用户和声誉,看看这是否是问题所在,事实并非如此。我现在正在使用MongoLab。所以我想知道这是否可能是问题之一,或者不是,或者是否有一种特定的方式来手动分配 MongoLab 中的用户管理员角色
您需要在 mongo shell 中授予对用户帐户的写入访问权限:
use krimson
db.grantRolesToUser(
"reportsUser",
[
{ role: "write", db: "krimson" }
]
)
我遇到了同样的错误。
所以尝试了下面的代码,它对我有用。
MongoCredential credential = MongoCredential.createCredential("xyz", "admin", "password".toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 1235), Arrays.asList(credential));
我得到了同样的错误,并通过设置authSource=admin来解决它
示例网址字符串
mongodb://root:example@localhost:27017/learningdb?authSource=admin&retryWrites=true&w=majority
用户已经拥有完全权限,Spring boot能够在启动时连接到mongoDB。问题是在从 mongo 存储库访问数据时,它无法对用户进行身份验证。提供身份验证源解决了这个问题。