如何使用GSSAPI认证机制访问MongoDB?

How to access MongoDB using GSSAPI authentication mechanism?

我正在尝试使用 c# 通过 ssl 证书连接到 MongoDB 服务器。我收到 System.TimeoutException(使用 CompositeServerSelector 选择服务器 30000 毫秒后发生超时)。

我开始通过 MongoClientSetting 对象进行连接。这是代码:

MongoClientSettings settings = new MongoClientSettings();
settings.MaxConnectionLifeTime = new TimeSpan(12, 0, 0);

settings.UseSsl = true;
settings.VerifySslCertificate = false;
var cert = new X509Certificate2("mongoDBCAFile.cer");
settings.SslSettings = new SslSettings{
    ClientCertificates = new[] { cert }
};

settings.Servers = new[]{
    new MongoServerAddress("xyz1.intranet.companyname.com", 12345),
    new MongoServerAddress("xyz2.intranet.companyname.com", 12345)
};

settings.ReplicaSetName = "replicaName";

var cred = MongoCredential.CreateGssapiCredential("username@intranet.companyname.com").WithMechanismProperty("SERVICE_NAME", "servicename");
settings.Credential = cred;

var client = new MongoClient(settings);

var database = client.GetDatabase("DatabaseName");
var collection = database.GetCollection<BsonDocument>("CollectionName");

//This is the place of error
var count1 = collection.CountDocuments(new BsonDocument());

我尝试使用 ConnectTimeout、SocketTimeout 和 wTimeOut,但错误都是一样的。

我也尝试过使用连接字符串来做同样的事情 但我不知道如何使用这么多参数创建连接字符串。

找到解决方案。

问题出在使用外部服务器对用户进行身份验证时。 MongoDB 服务器正在等待此外部服务器的许可,但由于身份验证从未成功,MongoDB 总是导致 System.TimeoutException。

这是修复代码。

settings.ReplicaSetName = "replicaName";

SecureString pwd = new NetworkCredential("intranet/userName", "myPassword").securePassword;
var cred = MongoCredential.CreateGssapiCredential("username/intranet.companyname.com", pwd).WithMechanismProperty("SERVICE_NAME", "serviceName").WithMechanismProperty("CANONICALIZE_HOST_NAME", "true");
settings.Credentials = cred;