Navigation

Search

Categories

On this page

Adding a Custom Key/Value Pair to Web.Config - Encrypting Sections of it

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 103
This Year: 41
This Month: 6
This Week: 2
Comments: 0

Sign In

 Thursday, April 24, 2008
Thursday, April 24, 2008 9:14:46 AM (Eastern Standard Time, UTC-05:00) ( )

The web.config file is commonly used to add database connection strings, mail server settings, system-wide settings etc.  It's easier to store such settings here rather than hard-code them within the pages for obvious reasons. Adding custom key/value pairs in the web.config is pretty easy. Just make sure that the <appSettings> section is outside of the <system.web> section.

<configuration>

<appSettings>
      <add key="myCity" value="Anchorage" />
</appSettings>
<system.web>
....
</system.web>

 

This key/value is accessed in your application like this:

Public Sub Page_Load()
         Dim strCity As String
         strCity = ConfigurationSettings.AppSettings("myCity")
End Sub

Another way to return a custom key's value is to pass the key name to a function.  This function also adds the key name and value to cache if it's not already there

'Return the value of the specified custom key, stored in the Web.Config file.
' If the value has been already requested before, the function returns its 
' cached value.
' The second optional parameter is the path of the Web.Config file where this 
' custom key is stored, and it is necessary to add a dependency to that file,
' so that the cached value is discarded if the file is edited.
' 
' Example: Dim myCity = GetCustomKeyValue("myCity") 

Function GetCustomKeyValue(ByVal key As String, Optional ByVal webConfigUrl As String = "/Web.Config") As String
    ' if this is not the first time this value is needed,
    '  we can find it in the cache
    Dim value As String = CType(HttpContext.Current.Cache(key), String) 

    ' if the retrieved string is empty, the value is not present into the cache,
    '  thus it is retrieved it from Web.Config, and then cached
    If value Is Nothing OrElse value = "" Then
        value = ConfigurationSettings.AppSettings(key)
        HttpContext.Current.Cache.Insert(key, value, New Caching.CacheDependency(webConfigUrl))
    End If 

    Return value
End Function

Lastly, ASP.NET 2.0 makes it really easy to encrypt parts of the web.config to secure sensitive parts of the file. Here are some articles on how to do it.

http://odetocode.com/Blogs/scott/archive/2006/01/08/2707.aspx

http://www.developerfusion.co.uk/show/5263/

http://channel9.msdn.com/Showpost.aspx?postid=134210

Not only can you encrypt config sections using aspnet_regiis from the command line, but you can also encrypt and unencrypt Web.config on the fly in code. The code for protecting and unprotecting sections in your Web.config is fairly trivial, because WebConfigurationManager-related classes handle all the work for you.  I added two buttons to a web page, called btnProtect and btnUnProtect, to protect and unprotect on the fly.  Here is the code of interest:

Protected Sub UnProtect_Click(ByVal sender As Object, ByVal e As EventArgs) 
    UnProtectSection("appSettings") 
End Sub 

Protected Sub Protect_Click(ByVal sender As Object, ByVal e As EventArgs) 
    ProtectSection("appSettings", "DataProtectionConfigurationProvider") 
End Sub 

Private Sub ProtectSection(ByVal sectionName As String, ByVal provider As String) 
    Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath) 
    
    Dim section As ConfigurationSection = config.GetSection(sectionName) 
    
    If section IsNot Nothing AndAlso Not section.SectionInformation.IsProtected Then 
        section.SectionInformation.ProtectSection(provider) 
        config.Save() 
    End If 
End Sub 

Private Sub UnProtectSection(ByVal sectionName As String) 
    Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath) 
    
    Dim section As ConfigurationSection = config.GetSection(sectionName) 
    
    If section IsNot Nothing AndAlso section.SectionInformation.IsProtected Then 
        section.SectionInformation.UnprotectSection() 
        config.Save() 
    End If 
End Sub 
 

Here is what the application settings look like when encrypted:

<appSettings configProtectionProvider=
        "DataProtectionConfigurationProvider">
  <EncryptedData>
   <CipherData>
    <CipherValue>
        AQAAANCMnd8BFdERjHoAwE/Cl+sBAAA
        AXmrl4EN1VUSGDS9ZSSydRwQAAAACAA
        AAAAADZgAAqAAAABAAAAA280OtZlZwu
        D3U+ihvi2zpAAAAAASAAACgAAAAEAAA
        AJ6AnDzWM1o3osh/Y6fcYtwAAQAA1PR
        +wzfwgBgZ4y0yHU4uxaaMET13u21Bv3
        zVE7aA7Z5pCWAYs54LNLNYQ673kmzAL
        osWb7OMuzW6BPwMp18gKNQXOFSGNgA1
        ...
    </< SPAN>CipherValue>
   </< SPAN>CipherData>
  </< SPAN>EncryptedData>
</< SPAN>appSettings>