Thursday, March 01, 2007

Impersonation using Code

      I was reading about impersonation and delegation. The most common way I found for impersonation is to write  a tag "<impersonate = "true" username="Name" password ="password" />"  in web.config file.  This will impersoname specific user to each request. I want to impersonate network user for only one request.

     In my project I have to create a directory which is shared on network and has rights set to network user. If I use impersonation in web.config file, all the request of my application executes under the rights of that network user ehich can be a security threat. I need to impersonate the user for a single request in which I need to create a directory on network shared location.

     Below is the code that impersonate the "Anonymous" (is explained in paragraph below code" user for perticular request.


HttpContext context = HttpContext.Current;   
// Get the service provider from the context           
 IServiceProvider iServiceProvider = context as IServiceProvider;
//Get a Type which represents an HttpContext           
Type httpWorkerRequestType = typeof(HttpWorkerRequest);
 // Get the HttpWorkerRequest service from the service provider           
// NOTE: When trying to get a HttpWorkerRequest type from the HttpContext           
// unmanaged code permission is demanded.           
HttpWorkerRequest httpWorkerRequest =
            iServiceProvider.GetService(httpWorkerRequestType) as HttpWorkerRequest;
 // Get the token passed by IIS           
IntPtr ptrUserToken = httpWorkerRequest.GetUserToken();
// Create a WindowsIdentity from the token           
WindowsIdentity winIdentity = new WindowsIdentity(ptrUserToken);           
Response.Write("Before impersonation: " + WindowsIdentity.GetCurrent().Name + "<br>");
// Impersonate the user           
WindowsImpersonationContext impContext = winIdentity.Impersonate();
Response.Write("Impersonating: " + WindowsIdentity.GetCurrent().Name + "<br>");
// Place resource access code here     
// Stop impersonating           
Response.Write("After Impersonating: " + WindowsIdentity.GetCurrent().Name + "<br>");

Fig - (1) Impersonate user using code.

     By saying  "Anonymous" user,  the user which is set for Anonymous account in IIS. By default this will be "IUser_MachineName".  Change this to Network user (or user you want to impersonate) by entering username and password and uncheck "Allow IIS to control password" check box.

   To do this click on "Start --> Run " and write " inetmgr". It will show IIS. Right click on virtual directory of your application and select property. Click on "Directory Security" tab. Click "Edit" button at "Anonymous Access and Authentication Cotrol" panel. Here you can change user name and password.

Happy programming.

No comments: