Click here to Skip to main content
15,878,809 members
Articles / Web Development / ASP.NET

Programmatic Adding Custom Encrypted Configuration Section in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.38/5 (8 votes)
11 Jul 2009CPOL5 min read 44.8K   282   29   11
It's important to understand that the web.config file in a web application is a secure place that no one can have access to that. So what can you do with your custom settings

Introduction

First of all, I would like to describe my headline and then skip into the article's main target.

So every ASP.NET web developer has some knowledge about ASP.NET configuration concepts and the main question is why we must use configuration in the applications? Perhaps this is a technique for segregating between the application and the settings of the application. The answer is yes. ASP.NET provides a wide variety of tools for configuring the application. This is a simple and human readable file in XML format named web.config file.

Background

Every web applications inherits the settings from the machine.config file and the root web.config file. I mean you can apply settings to single web applications or individual web applications. For example, you set some of the custom error pages, type of debugging, default language and more. But this is not just everything the web.config can do for us. You can make a custom application setting and bind a custom value to it and then use it in every place in your application.

It's important to understand that the web.config file in a web application is a secure place that no one can access because the applications most important information is stored in the web.config file. For example, application database connection string is one of the dangerous information that is placed in web.config file and if anyone can access it, perhaps she/he can access the application's backend and this is not desirable for a web developer.

Using the Code

Now let's break and back to the headline. Imagine you need to store some kind of custom information in your application configuration file. What is the best solution to do this? My answer is using some tools that ASP.NET provides for helping us in these type of solutions. However you can choose other types of storage such as custom XML files or something else.

ASP.NET provides the WebConfigurationManager class in the System.Web.Configuration namespace, which allows you to extract information from a configuration file at runtime. The WebConfigurationManager class is my starting point. It provides some members for managing the configuration settings, we use a useful method whose name is OpenWebConfiguration().

This method returns a configuration object that provides access to the configuration information for the specified web application. Now let's consider the following example:
In this example I loop over the connection string(s) of my application database(s) with WebConfigurationManager class and ConnectionStrings property:

C#
protected void Page_Load(object sender, EventArgs e)
{
    foreach (ConnectionStringSettings connStr in 
        WebConfigurationManager.ConnectionStrings)
    {
        Response.Write("Name : " + connStr.Name + "<br/>");
        Response.Write("Connection String : " + 
           connStr.ConnectionString + "<br/><br/>");
    }
}

Note that the ASP.NET applications have a built-in connection string that refers to the ASP.NET native database for using membership.

Now let's begin with the programmatic adding custom application configuration settings in unprotected state and then I explain how to protect it using data protection providers.

Writing Configuration Sections

Imagine I have custom settings in my application for a custom service provider. This service has a unique URI, serving status and the port number.
Now look at the following web.config body:

XML
<configuration>
    <configSections>
        <sectionGroup name="someSectionName">
            .
            .
            .
        </sectionGroup>      

        <section name="customServiceProvider" 
        type="CustomServiceProvider" />
    </configSections>       

    <customServiceProvider uri="someUri" status="someStatus" 
        port"somePort" />
        </configuration>

As you see in this example, web.config file has two different parts of the declaration for a custom section. A section must present between <configsections> tags and then write your own section with custom attributes outside of the <configsections> tag.

Now let's go back to the code and write custom sections class and then use it. In the App_Code folder of the application, I define a class with the name of the section's type:

XML
<section name="customServiceProvider&
    type="CustomServiceProvider" />

Now you must create a custom class for providing the custom section. Look at the following code of the CustomServiceProvider section class:

C#
using System.Configuration;

public class CustomServiceProvider : ConfigurationSection
{
    [ConfigurationProperty("uri",
        IsRequired = true)]
    public string Uri
    {
        get { return (string)base["uri"]; }
        set { base["uri"] = value; }
    }

    [ConfigurationProperty("status",
    IsRequired = true)]
    public string Status
    {
        get { return (string)base["status"]; }
        set { base["status"] = value; }
    }

    [ConfigurationProperty("port",
        IsRequired = false,
        DefaultValue = 8081)]
    public int Port
    {
        get { return (int)base["port"]; }
        set { base["port"] = value; }
    }
}

As you see in this example, the custom section must extend the ConfigurationSection class and then write its own attributes of the section.

Now you can run the application and ASP.NET compiles the code behind and makes the custom section in the web.config file.
This is a custom section that is stored in the web.config file, and you can use it anywhere you need in your application. But this information is not encrypted and this is a clear text in the web.config file. However no one can access this file, but sometimes in some solutions you must prevent web.config file from providing a clear text mode of some configuration. In this case, we can protect the target configuration by using the ASP.NET protection providers.

Encrypting Configuration Sections

Now I have a web.config file with some application configurations and one custom section that is used in the application.

ASP.NET supports two encryption options, RSA and DPAPI (Data Protection API). Each of them has some attributes and using of any option has advantages and disadvantages. But with both of these options, encryption is completely transparent. When you retrieve a section from an encrypted section, ASP.NET automatically performs the decryption and returns the plain text to your code. Similarly, if you modify a value programmatically and save it, Encryption is performed automatically, however you won't be able to edit that section of the web.config file by hand.
To enable encryption programmatically, you need to retrieve the corresponding ConfigurationSection.SectionInformation object and then call the ProtectSection() method. Finally you must save your changes to the web.config file with Save method.

C#
Configuration config = WebConfigurationManager.
    OpenWebConfiguration("~/");
if (config.HasFile)
{
    // load custom section to the object
    CustomServiceProvider csp =
        (CustomServiceProvider)config.
        GetSection("customServiceProvider");

    // now if you request for encrypt config section
    if (chkEncryptSection.Checked)
    {
        if (!csp.SectionInformation.IsProtected)
            csp.SectionInformation.ProtectSection
                ("DataProtectionConfigurationProvider");
        config.Save();
        Response.Write("Protected");
    }
    else
    {
        if (csp.SectionInformation.IsProtected)
            csp.SectionInformation.UnprotectSection();
        config.Save();
        Response.Write("Unprotected");
    }
}

Note that you must have permission to modify the web.config file in IIS. If you don't have write permission, ASP.NET throws an exception when you try to save your configuration changes to the web.config file.

Now you can open the web.config file and look at the section that you write by hand. When you call the ProtectSection method in your custom section, ASP.NET makes your custom section change automatically as you see in the following:

XML
<customServiceProvider 
        configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
        <CipherData>
            <CipherValue>
        AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAARtfFfaze+ECMAzsB
        9bA3gwQAAAACAAAAAAADZgAAqAAAABAAAAASYRaZz13
        dR3uFCHuq81B+AAAAAASAAACgAAAAEAAAANFWRbT75ox
        I98VqV5EEkMy4AAAA3NPtD0IkBPyJ7+HVifr7aVj/GCJElu6GJmA
        uwoZVqAjiw+Gv6MJwsAo3AseZLkq6QuUwyd+0NiZeC3BUM7YH
        iQ6LgVmhV4qOPupRwRjb6G7YTHxDLRzSvClPpT6ZqrqCKAPtm5J
        z3y+Aw8UNVIL0cqjHew8uSuaCuex4DNrAjFDUiW8npgeEaSCFh6w
        vYo7uL+9NYgRjoK+Eb+8kbhASF8CeEdQyQ4agrns9zBV8aY6Ae0
        J0/SytqBQAAABXXOupMvRAEzjJprdUiEzQlWcAZg==
            </CipherValue>
        </CipherData>
    </EncryptedData>
</customServiceProvider> 

Encrypting the Connection String

Remember you can protect any section of your web.config file, and this is the example of the encrypting ConnectionString option in the application configuration file (web.config).
Look at the following example:

C#
Configuration config = WebConfigurationManager.
    OpenWebConfiguration("~/");
if (config.HasFile)
{
    // load the connection string section 
    // to the object and then encrypt or decrypt it.
    ConfigurationSection connStr =
        config.GetSection("connectionStrings");
    if (chkEncryptConnStr.Checked)
    {
        if (!connStr.SectionInformation.IsProtected)
            connStr.SectionInformation.ProtectSection
                ("DataProtectionConfigurationProvider");
        Response.Write("Protect ConnectionString.");
    }
    else
    {
        if (connStr.SectionInformation.IsProtected)
            connStr.SectionInformation.UnprotectSection();
        Response.Write("Unprotected ConnectionString.");
    }
    config.Save();
}

Remember you can use your connection string config anywhere you need.

History

  • 11th July, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Atra Inc
Iran (Islamic Republic of) Iran (Islamic Republic of)
Software developer and programming with .Net framework tech.
Managing Director of the Atra Inc in Tabriz/Iran that serves some Software Solution's.

Comments and Discussions

 
GeneralExcellent! Pin
Abbas_Riazi15-Jul-09 17:56
professionalAbbas_Riazi15-Jul-09 17:56 
GeneralRe: Excellent! Pin
mheidari16-Jul-09 0:25
mheidari16-Jul-09 0:25 
tank u so much Rose | [Rose]

If you think you has fallen out of an elephant's nose ; I make you a donkey

GeneralMy vote of 1 Pin
George Zorba15-Jul-09 4:40
George Zorba15-Jul-09 4:40 
GeneralRe: My vote of 1 Pin
mheidari16-Jul-09 0:24
mheidari16-Jul-09 0:24 
GeneralDeployment Pin
brandon.peterson14-Jul-09 8:11
brandon.peterson14-Jul-09 8:11 
GeneralRe: Deployment Pin
mheidari14-Jul-09 22:42
mheidari14-Jul-09 22:42 
GeneralRe: Deployment Pin
brandon.peterson15-Jul-09 8:07
brandon.peterson15-Jul-09 8:07 
GeneralRe: Deployment Pin
MaxZ15-Sep-10 4:33
MaxZ15-Sep-10 4:33 
Generalbad format Pin
Emilio Garavaglia10-Jul-09 23:45
Emilio Garavaglia10-Jul-09 23:45 
GeneralRe: bad format Pin
mheidari11-Jul-09 2:54
mheidari11-Jul-09 2:54 
GeneralRe: bad format Pin
Emilio Garavaglia13-Jul-09 0:13
Emilio Garavaglia13-Jul-09 0:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.