问题
I would like to move my authentication over from sha-1 to sha 256, however, even though I've created a hasher I get an error stating that its unable to authenticate using sha1. There is no reference in the code to this old mechanism and I've already created a sha256 user in my mongo DB. Which means it is being defaulted to the old version somehow. Looking at the code I get warnings stating that MongoClientSettings is obsolete but browsing the web I don't see an alternative unless I'm meant to be using a connection string instead? The documentation for mongo client still accepts a mongoClientSettings in the constructor? Im using MongoDB version 4.10 and mongocsharpdriver 2.10
public static MongoClientSettings PrepareMongoSettings(string dbName)
{
MongoClientSettings mongoSettings = new MongoClientSettings();
mongoSettings.Server = new MongoServerAddress(Host, Port);
mongoSettings.ConnectionMode = 0;
if (!string.IsNullOrWhiteSpace(MongoUsername))
{
List<MongoCredential> mongoCredentials = new List<MongoCredential>();
MongoCredential mongoCred = MongoCredential.CreateCredential("admin", MongoUsername, MongoPassword);
mongoCredentials.Add(mongoCred);
mongoSettings.Credentials = mongoCredentials;
}
return mongoSettings;
}
The hasher that I have created is pretty basic the password should get hashed for before this code it is entered into the DB.
public static class HasherSha256
{
public static byte[] GetPasswordHash(string username, string password)
{
// get salted byte[] buffer, containing username, password and some (constant) salt
byte[] buffer;
using (System.IO.MemoryStream stream = new MemoryStream())
using (System.IO.StreamWriter writer = new StreamWriter(stream))
{
writer.Write("MyDB");
writer.Write(username);
writer.Write(password);
writer.Flush();
buffer = stream.ToArray();
}
return ComputeSha256Hash(buffer);
}
static byte[] ComputeSha256Hash(byte[] rawData)
{
using (SHA256 sHA256 = SHA256.Create())
{
return sHA256.ComputeHash(rawData);
}
}
}
}
回答1:
I dont see any documentation that says MongoClientSettings
is obsolete. It is very much an available feature for connecting to MongoDB. See Documentation here. Credentials
was deprecated but replaced with Credential
which takes only one credential.. not an array.
new MongoClientSettings()
{
ConnectionMode = ConnectionMode.ReplicaSet,
Credential = MongoCredential.CreateCredential("admin", Username, Password),
ReplicaSetName = "ReplicaSetName",
Servers = new List<MongoServerAddress>(){new MongoServerAddress("server", 27017), new MongoServerAddress("server2", 27017)}.ToArray(),
ApplicationName = "AppName",
}
来源:https://stackoverflow.com/questions/60328605/mongo-db-sha-1-to-sha256