Securing your data in Web.config
Why use Web.config instead of say database?
There are some advantages for storing data in web.config files.
- There are some things for instance database connection string that cannot be stored in a database.
- Storing data inside the code as Constants or Enums mean that it will be difficult to change it for various environments.
How secure is web.config before?
The IIS Server will not serve the web.config file to the client. It is part of your source control, meaning a person having access to it will also have access to your API source code. So, it is somewhat secure file.
How do we secure it
There are options to secure entire sections of web.config files. But my approach is to encrypt the data string and store it in the config file.
- Create a helper function for decrypting and encrypting data based on a key.
- Encrypt your data with a key and store the encrypted string in the web.config.
- Use a helper function like the one below to decrypt the keys at runtime.
private const readonly string decryptKey = "";
public string GetFromConfig(string key)
{
var encryptedText = System.Web.Configuration.WebConfigurationManager.AppSettings[key];
var plainText = Decrypt(encryptedText, decryptKey);
return plainText;
}
In this method, the decryption key will be stored in the code and is common for all the environments. But it allows you to change the data in the web.config without the need to recompile the application.
As a bonus, you can change the decryption key and with it the encrypted data with each version / release to further improve security.
This blog post is based on my answer in SO.