MongoDB - 命令失败,错误代码为13`未经*****授权执行此命令`

时间:2016-01-18 21:43:44

标签: java mongodb mlab

因为一些奇怪的原因,我的用户没有被授权在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分配用户管理员角色

3 个答案:

答案 0 :(得分:1)

您需要在mongo shell中授予用户帐户的写访问权限:

use krimson
db.grantRolesToUser(
    "reportsUser",
    [
      { role: "write", db: "krimson" }
    ]
 )

答案 1 :(得分:0)

我遇到了同样的错误。

所以尝试了下面的代码,它对我有用。

MongoCredential credential = MongoCredential.createCredential("xyz", "admin", "password".toCharArray());
        MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 1235), Arrays.asList(credential));

答案 2 :(得分:0)

我遇到了相同的错误,并通过设置authSource = admin

解决了该错误

示例网址字符串 mongodb:// root:example @ localhost:27017 / learningdb?authSource = admin&retryWrites = true&w = majority

用户已经具有完全权限,并且Spring Boot能够在启动时连接到mongoDB。问题是从mongo存储库访问数据时,它无法验证用户身份。提供authSource解决了该问题。