【问题标题】:MongoDB user authentication performing actionsMongoDB 用户身份验证执行操作
【发布时间】:2014-09-26 23:11:29
【问题描述】:

我已经为我的研究安装了 MongoDB,并创建了数据库:mydb、jobs

我创建了一个用户:

db.createUser( { user: "devdbuser", pwd: "123456", roles: [ "readWrite" ] } )

然后在我的 java 代码中我正在尝试:

MongoClient client = new MongoClient(Arrays.asList(new ServerAddress[] { new ServerAddress("localhost", 27017)}),
                             Arrays.asList(new MongoCredential[] { MongoCredential.createMongoCRCredential("devdbuser", "mydb", "123456".toCharArray()) } ));

DB myDB = client.getDB("jobs"); // Here I get the jobs DB with user I created for 'mydb'

DBCollection collection = myDB.getCollection("myfirstcollection");
collection.insert((DBObject)JSON.parse("{\"name\": \"First user\", \"email\": \"first_user@mail.com\"}"));

client.close();

请注意,当我创建 MongoClient 时,我请求连接到“mydb”,并为创建的用户提供凭据。 但是当我使用作业数据库并尝试将数据插入集合时,一切正常。

我希望用户没有权限的错误,我错过了什么吗?

感谢您的帮助。

【问题讨论】:

    标签: mongodb mongodb-java


    【解决方案1】:

    您已创建具有readWrite 角色的用户devdbuser。因此devdbuser 获得了read 的所有权限,并具有修改所有非系统集合的数据的能力。

    【讨论】:

      【解决方案2】:

      如果您尝试使用“jobs”数据库而不是“mydb”创建凭据,则身份验证将失败。

      MongoClient client = new MongoClient(Arrays.asList(new ServerAddress[] { new ServerAddress("localhost", 27017)}),
          Arrays.asList(
      new MongoCredential[] { MongoCredential.createMongoCRCredential("devdbuser", 
      "jobs", "123456".toCharArray()) } ));
      

      错误堆栈跟踪

      com.mongodb.CommandFailureException: { "serverUsed" : "localhost/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "auth failed" , "code" : 18}
      

      基本上用户一旦在“mydb”上通过身份验证,但对跨数据库的集合具有读写权限

      【讨论】:

        猜你喜欢
        • 2020-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多