Click here to Skip to main content
15,879,474 members
Articles / Programming Languages / C# 4.0

Accessing impersonated user’s details from code behind in C#

Rate me:
Please Sign up or sign in to vote.
4.77/5 (4 votes)
7 May 2013CPOL1 min read 18.3K   8   3
This post explains how to access an impersonated user's details from the code-behind using C#.

In web development, config files play a very important role. Reading config file entries in a code-behind file is a very common thing in web development. 

Config entries are stored in the web.config file in the <appSettings> tag and can be accessed using System.Configuration.ConfigurationManager.AppSettings["keyName"];.

There might be a case when we may have to access the impersonated user’s details in our code. These details cannot be accessed using ConfigurationManager.AppSettings[]

To access the Impersonated user’s details, we use the classes in the namespaces System.Web.Configuration and System.Configuration.

First, we access the configuration file as a Configuration object using the WebConfigurationManager.OpenWebConfiguration("pathToConfigFile") method. The WebConfigurationManager class is defined in the System.Web.Configuration namespace.

Then we get the identity section from the config file to retrieve the user details. This is achieved using the IdentitySection class defined in System.Web.Configuration namespace and "GetSection()" method of "Configuration" class.

The GetSection() method returns the ConfigurationSection object specified in the parameter to the method. The return object is to be type cast into the required object type, in this case IdentitySection.

Then IdentitySectionObject.propertyName gives the value of the corresponding property.

The complete sample code is as shown. I have written the code in the Page_Load method. 

C#
using System.Web.Configuration;
using System.Configuration;
 
protected void Page_Load(object sender, EventArgs e)
{
    Configuration objConfigFile;
    //getting an instance of the configuration file
    objConfigFile = WebConfigurationManager.OpenWebConfiguration(
                           HttpContext.Current.Request.ApplicationPath);

    //getting an instance of the "identity" section of the cofiguration file
    IdentitySection objIdentitySection = 
      (IdentitySection)objConfigFile.GetSection("system.web/identity");

    if (objIdentitySection != null)
    {
        string username = objIdentitySection.UserName;
        string password = objIdentitySection.Password;
        bool impersonate = objIdentitySection.Impersonate;
        Configuration currentConfiguration = objIdentitySection.CurrentConfiguration;

        //Obviously you won't be doing this. The lines below are just for testing purpose
        lblUsername.Text = username;
        lblPassword.Text = password;
        lblImpersonateOrNot.Text = impersonate.ToString();
    }
} 

The entry in the web.config file is as given below:

XML
<system.web>
    <identity impersonate="true" 
       userName="YourDomain\YourUserName" password="YourPassword" />
</system.web>

Obviously, you would not be printing the username and password on the screen. I have just included that for testing purpose. I have uploaded a sample website folder in a zip file. You can refer to that. 

Make sure you specify the domain of the computer in the username part because if you specify only the username, there is a chance that you might get a runtime exception saying: 

Could not create Windows user token from the credentials specified in the config file. 
Error from the operating system ‘Logon failure: unknown username or bad password'. 

Hope this helps!! 

License

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


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionQuestion regarding the keyword use impersonate="true" Pin
Tridip Bhattacharjee7-May-13 6:07
professionalTridip Bhattacharjee7-May-13 6:07 
AnswerRe: Question regarding the keyword use impersonate="true" Pin
Amogh Natu7-May-13 19:42
professionalAmogh Natu7-May-13 19:42 
Thanks for your comment.

It's not necessary to use impersonation in websites. Impersonation is used only when the website accessing user needs to be given access to some particular resources on the server only for some period of time.

So instead of explicitly giving that user access to the resources every time, the server impersonates the external user as another user (for that period of time) who has access rights to the resources.

Only if you have such a scenario in your website, you would want to use impersonation. Else, it is not really required.
Thanks,
Amogh Natu.

GeneralRe: Question regarding the keyword use impersonate="true" Pin
Tridip Bhattacharjee7-May-13 20:50
professionalTridip Bhattacharjee7-May-13 20:50 

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.