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;
IServiceProvider iServiceProvider = context as IServiceProvider;
Type httpWorkerRequestType = typeof(HttpWorkerRequest);
HttpWorkerRequest httpWorkerRequest =
iServiceProvider.GetService(httpWorkerRequestType) as HttpWorkerRequest;
IntPtr ptrUserToken = httpWorkerRequest.GetUserToken();
WindowsIdentity winIdentity = new WindowsIdentity(ptrUserToken);
Response.Write("Before impersonation: " + WindowsIdentity.GetCurrent().Name + "<br>");
WindowsImpersonationContext impContext = winIdentity.Impersonate(); Response.Write("Impersonating: " + WindowsIdentity.GetCurrent().Name + "<br>");
impContext.Undo();
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.