简体   繁体   中英

How to secure smtp info with Azure and Github?

I have a small website which has a Contact Me page, for this page I use System.Net.Mail and I followed this tutorial .

My problem now is that I host my website on Azure and use Github as source control and deployment.

The problem is of course that all of my code would be public on Github and that the credentials are out in the open.

How can I secure this info from the public with Azure? I have been looking into the App Settings section but I'm not 100% sure how to handle this properly.

  <system.net>
    <mailSettings>
      <smtp from="mail@outlook.com">
        <network host="smtp-mail.outlook.com"
                 port="587"
                 userName="mail@outlook.com"
                 password="notarealpassword"
                 enableSsl="true" />
      </smtp>
    </mailSettings>
  </system.net>

So the easiest way would be to use App Settings (just like you said). You would create several app settings like username = mail@outlook.com and those will become environment variables on the VM's hosting your WebApp. You could grab the value or those environment variables by the name of the variable in any way that you like.

I was doing this:

Environment.GetEnvironmentVariable("StorageConnectionString")

I based my solution on the advice from 4c74356b41 's answer.

Step 1: Add keys to your Web.config file

Leave the value's empty.

  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="EmailAccount" value=""/>
    <add key="EmailPassword" value=""/>
  </appSettings>

Step 2: Use the keys in your code

With ConfigurationManager you can call AppSettings and retrieve the value based on the key name.

       using (var smtp = new SmtpClient())
        {
            var credential = new NetworkCredential
            {
                UserName = ConfigurationManager.AppSettings["EmailAccount"],  
                Password = ConfigurationManager.AppSettings["EmailPassword"]  
            };
            smtp.Credentials = credential;
            smtp.Host = "smtp-mail.outlook.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            await smtp.SendMailAsync(message);
            return RedirectToAction("Sent");
        }

Step 3: Add your Key Value's to your App settings on Azure

In your Web App, go to Application Settings under the Settings and add your key/value's

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM