Credential Caching issue
I have a static helper method that I wrap around SMTPClient to send开发者_C百科 email.
I am storing the SMTP authentication in the web.config -> in the default location that System.Net namespace objects look for.
I am passing the credentials to the SMTPClient, because I want to run my password decryption on the password before the SMTPClient uses this.
The issue that I'm encountering here is - when I run this once, the password is stored somehwere as "decrypted" somehow in the cache. When I try and run this method a second time in the same session, I get an error, because it's trying to decrypt a password that was already decrypte the first time it was ran. Any ideas?
public static void SendEmail(MailMessage mailMessage)
{
SmtpClient smtpClient = new SmtpClient();
NetworkCredential nc = new NetworkCredential();
nc = (NetworkCredential)smtpClient.Credentials;
nc.Password = Tools.Decrypt(nc.Password);
smtpClient.Credentials = nc;
smtpClient.Send(mailMessage);
nc = null;
smtpClient.Credentials = null;
}
As NetworkCredentials is a class you are passing a reference of to your nc variable this means when you decrypt the password you are decrypting it on the original object.
You either need to clone the object or only do this once when your application starts.
A little bit hacky but just putting
SmtpClient smtpClient = new SmtpClient();
NetworkCredential nc = new NetworkCredential();
nc = (NetworkCredential)smtpClient.Credentials;
nc.Password = Tools.Decrypt(nc.Password);
smtpClient.Credentials = nc;
smtpClient = null;
in you global.asax might do it. And then having
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
smtpClient = null;
in you static method, though I'm sure there must be a more elegant solution.
Update: You could probably try using SmtpNetworkElement and updating the password on this in the global.asax - I think as long as you do this before you use SmtpClient it may work.
精彩评论