CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Identity Impersonate at Code Level in ASP.Net
Submitted By Satheesh Babu B
On 10/20/2008 7:15:58 AM
Tags: asp.net,CodeDigest  

There are scenarios where it is required to impersonate the asp.net thread to run on different identity for executing some specific operations.

 

<identity impersonate="true" />

 

The above config setting will make sure that the asp.net is always running under the identity of the user who is connecting the application. Most of the time, our application will have a separate service account which is the asp.net uses for execution. At times, we will have requirements to execute a block of code/Operations to run under the identity of the user who is logged in. This can be done by impersonating the logged in user in code level before beginning to execute that particular block of code.

                       

  WindowsIdentity wId = (WindowsIdentity)HttpContext.Current.User.Identity;

        WindowsIdentity wIdb4 = WindowsIdentity.GetCurrent();

        string name = wIdb4.Name;

        Response.Write("Before impersonation"+name +"<br>");// <-- Writes ASPNET Account

 

 

        //Till this line,code is executed in the context of worker process

        WindowsImpersonationContext wIdCon = wId.Impersonate();

        WindowsIdentity wIdafter = WindowsIdentity.GetCurrent();

        name = wIdafter.Name;

        Response.Write("After Impersonation " + name + "<br>");// <-- writes Logged in user

 

            //Run in the context of logged authenticated user, do your //operations that require impersonation

 

        wIdCon.Undo();

        WindowsIdentity wIdafterUndo = WindowsIdentity.GetCurrent();

        name = wIdafterUndo.Name;

 

        Response.Write("After undo Impersonation " + name + "<br>");

 

OUTPUT

Before impersonation SERVER\ASPNET
After Impersonation TestAccount
After undo Impersonation SERVER\ASPNET

 

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..