Share via


Cloud Tip #5-Secure your settings in Web.config with Encryption

In Windows Azure and especially with SQL Azure we need to store passwords to access things. I wanted to show how you can encrypt the web.config file by adding code to the global.asax file. The cool part of this is that using this technique you can secure application specific settings like connection strings and other data in the unlikely event that someone is able to get a copy of the configuration file (like by copying it to a thumb drive from the host machine or something similar).

The basic logic is to create a variable that points to a configuration section, then checking that the section is protected (i.e. encrypted). If it isn't, then call the ProtectSection method to encrypt the contents. The server uses the local DPAPI (Data Protection API) to encrypt the configuration section with a machine specific key, so only that machine can decrypt the contents. The code to add to the global.asax.cs file in the Application Start event for this is:

 protected void Session_Start(object sender, EventArgs e) 
{ 
    EncryptSection("appSettings"); 
} 
     
private void EncryptSection(string sSection)
{
    Configuration config = System.Web.Configuration
                             .WebConfigurationManager
                             .OpenWebConfiguration
                             (Context.Request.ApplicationPath);

    ConfigurationSection configSection =
        config.GetSection(sSection);

    if (!configSection.SectionInformation.IsProtected)
    {
        configSection.SectionInformation.ProtectSection
        ("DataProtectionConfigurationProvider");
        config.Save();
    }
}

Happy Coding!

Digg This

Comments

  • Anonymous
    July 24, 2012
    Don't think that the DPAPI would work in Azure since it relies on machine-specific data for encryption.  Should we not use the RSAProtectedConfiguration provider instead, and make sure we have a machineKey element in the web.config, so we can scale out the app?Also, by encrypting the web.config in session_start, this means the config could be updated by multiple user sessions.  And I don't think the appPool identity user has access to the file system in order to save the web.config, unless this is granted by a startupTask for the web role.I think a better approach might be to abstract this code out to a static method that gets run via the WebActivator during the app PreInit.  Way before the application starts, so you don't get an infinite loop of app startups due to changing web.config.HTH