这件事现在会让我发疯。我试图让它工作 3 个小时,但没有任何结果。我安装了 mongodb 2.8rc4。我在 admin db 中创建了一个用户帐户。我可以使用 mongo localhost/agp -u dato0011 -p "MyPassword"连接到 mongod。我可以通过 db.auth 对其进行身份验证,但由于未知原因,这在 C# 驱动程序中不起作用。
连接字符串是 mongodb://dato0011:MyPWD@localhost/agp
我使用以下代码初始化数据库:
var client = new MongoClient(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
var server = client.GetServer();
var db = server.GetDatabase("agp");
但是当我尝试保存时,出现异常:
Unable to connect to server 192.168.0.100:27017: Invalid credential for database 'agp'..
在内部异常的深处,有这条消息:
{ “认证”:1,“用户”:“dato0011”,“随机数”:“fc65b3c269560533”,“ key ”:“35589d31830b76c72358343bc054105f” }
还有这个
{"Command 'authenticate' failed: auth failed (response: { \"ok\" : 0.0, \"errmsg\" : \"auth failed\", \"code\" : 18 })"}
有人知道我做错了什么吗? 谢谢。
更新
不知道是否有帮助,但这是抛出异常的代码:
Users.Save(user);
用户在哪里
Users = db.GetCollection<User>("users", WriteConcern.W1);
更新 2 显然,异常消息有点误导。驱动程序确实连接到 mongod,但由于未知原因无法进行身份验证。用户名和密码参数正确传递。这是 admin 数据库中的用户。
> db.system.users.find().toArray()
[
{
"_id" : "agp.dato0011",
"user" : "dato0011",
"db" : "agp",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "GjlDJOiKf2Xn1VO/1MhWXA==",
"storedKey" : "vAi30QZLFkCZf6ISm5TIfIWPwZY=",
"serverKey" : "DBmbbRLrLXEIxFCuZ52VaSnRWwo="
}
},
"roles" : [
{
"role" : "readWrite",
"db" : "agp"
},
{
"role" : "dbAdmin",
"db" : "agp"
}
]
最佳答案
在 MongoClientSettings 上使用 MongoCredentials -
string username = "user";
string password = "password";
string mongoDbAuthMechanism = "SCRAM-SHA-1";
MongoInternalIdentity internalIdentity =
new MongoInternalIdentity("admin", username);
PasswordEvidence passwordEvidence = new PasswordEvidence(password);
MongoCredential mongoCredential =
new MongoCredential(mongoDbAuthMechanism,
internalIdentity, passwordEvidence);
List<MongoCredential> credentials =
new List<MongoCredential>() {mongoCredential};
MongoClientSettings settings = new MongoClientSettings();
// comment this line below if your mongo doesn't run on secured mode
settings.Credentials = credentials;
String mongoHost = "127.0.0.1";
MongoServerAddress address = new MongoServerAddress(mongoHost);
settings.Server = address;
MongoClient client = new MongoClient(settings);
关于c# - MongoDB 可以从 mongo 客户端连接,但不能从 C# 驱动程序连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27747503/