如何检查数据库是否需要auth

时间:2014-07-20 08:33:25

标签: javascript node.js mongodb mongodb-query

我正在开发一个允许用户登录mongodb数据库的项目。基本上我有

db.authenticate(username, password, function(err, isAuthPass) {...}

检查用户是否通过了身份验证。但是,有时服务器不需要身份验证。如果我提供用户名/密码,它将失败。所以我需要知道如何使用mongo-native-client检查auth模式。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

好吧,我想你可以直接询问数据库中的配置信息。这确实伴随着你应该使用"测试/失败"之前讨论过的方法,因为您无法从启用了身份验证的服务器获取此信息,该服务器未在localhost上运行:

var mongo = require('mongodb'),
    MongoClient = mongo.MongoClient;


MongoClient.connect('mongodb://localhost:30000/test',function(err,db) {

  var adminDb = db.admin();

  adminDb.command({ "getCmdLineOpts": 1 },function(err,result) {
    console.log( JSON.stringify( result, undefined, 4 ) );
  });

});

这显示"解析"选项,它们是从命令行实际发送还是从配置文件中获取并不重要,如此处的输出所示:

{
    "documents": [
        {
            "argv": [
                "mongod",
                "--config",
                "mongod.conf"
            ],
            "parsed": {
                "config": "mongod.conf",
                "net": {
                    "bindIp": "0.0.0.0",
                    "port": 30000
                },
                "security": {
                    "authorization": "enabled"
                },
                "storage": {
                    "dbPath": "data"
                },
                "systemLog": {
                    "destination": "file",
                    "logAppend": true,
                    "path": "log/mongod.log"
                }
            },
            "ok": 1
        }
    ],
    "index": 338,
    "messageLength": 338,
    "requestId": 25,
    "responseTo": 3,
    "responseFlag": 8,
    "cursorId": "0",
    "startingFrom": 0,
    "numberReturned": 1
}

因此,"security.authorization.enabled": true的存在告诉您进一步的操作将需要提供授权凭证。

另请参阅对您的工具有用的getCmdLineOpts和其他diagnostic information commands

答案 1 :(得分:0)

有时?总是使用密码。如果您不需要一个,就像您的本地环境一样,您应该使用该环境的配置文件,例如具有该环境凭据的./config/dev.js