问题
I am writing a C# class that needs to send SMTP emails. I found code in this SO question which gave me what I needed to send the email (SO Question)
For convenience, here is the code I am modifying from an answer to the above question:
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
The problem I have is that the code in that question requires the smtp password to be stored in the plain-text C# source file. Problem one is that this code will be checked in to team foundation service so the whole team would have to/get to know the credentials. Problem two is that obfuscation is possible but it doesn't fix problem 1.
The closest to a solution i have found is encryption of an app config as an installation step. This doesn't get around problem 1 but if necessary can be done.
Does this situation come up in production applications, and what best practices are used to store passwords needed to instantiate C# classes?
回答1:
We solve this issue using our build server, TeamCity. The build system contains production secrets (passwords, API Keys, etc), which can only be set up by a few trusted individuals. Our build system is then responsible for altering the configuration (and other sensitive) files just before/after compilation using scripts and/or Password Build Parameters.
This frees us up to commit staging/test values for our secrets, but know that production builds will get production secrets. App/Web.Config transforms can take care of URL switching (dev/qa/stage/prod), so we only use the build server for the parts that we don't want included in source control, ever.
回答2:
It only accept plain text, ie
Credentials = new NetworkCredential(fromAddress.Address, "MY Password" )
When you deploy the project, no one will be able to see your password. If you save it to a text file then you can use an encryption method to prevent others from viewing your password, but if you parse it as a parameter to the Credentials, then you have to parse it as a plain text. It's the usual way we professionally do. If you are unwilling to give your mail password ,then create another email account for test and place it's credentials in there.
来源:https://stackoverflow.com/questions/17246364/how-do-i-securely-store-and-set-password-for-use-by-smtpclient-class