使用下面的示例代码 https:/github.commongodbnod-mongodb-nativeblob5a1b61c9f2baf8f6f3cec4c34ce2db52272cd49ddocsreferencecontenttutorialsconnectauthenticating.md。我的代码就像下面一样简单,但却抛出了"MongoServerSelectionError: InitializeSecurityContext: 指定的目标未知或无法到达".
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const fs = require("fs");
// KDC Server
const server = "linux.mydomain";
const principal = "myname@mydomain";
const urlEncodedPrincipal = encodeURIComponent(principal);
const dbName = "devDB"
const url = `mongodb://${urlEncodedPrincipal}@${server}/${dbName}?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:mongodb,CANONICALIZE_HOST_NAME:false,SERVICE_REALM:windows`;
const caChain = fs.readFileSync("./ssl/ca-cert.pem");
let mongoConnectOptions = {
ssl: true,
sslValidate: true,
sslCA: caChain,
useNewUrlParser: true,
useUnifiedTopology: true,
replicaSet: "myReplica"
};
const client = new MongoClient(url, mongoConnectOptions);
// Let's write the actual connection code
client.connect(function(err) {
assert.equal(null, err);
client.close();
});
而package.json的内容如下。
{
"name": "Try_Connect",
"version": "1.0.0",
"description": "",
"main": "Connect.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"fs": "0.0.1-security",
"kerberos": "^1.1.3",
"mongodb": "3.5.5"
}
}
根据我的理解,MongoDB服务器也应该作为代理向KDC服务器发送认证请求,所以不需要在客户端配置这些。不知道这个错误是和这个有关还是和 replicaSet 的 URL 不正确有关?
谢谢,谢谢
看来这个问题是最新版本的mongodb驱动和或kerberos库的bug,因为降级解决了这个问题。
git diff .\package.json
diff --git a/package.json b/package.json
index d0172a7..0c893b4 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
"license": "ISC",
"dependencies": {
"fs": "0.0.1-security",
- "kerberos": "^1.1.3",
- "mongodb": "3.5.5"
+ "kerberos": "1.1.2",
+ "mongodb": "3.1.13"
}
}