DCSIMG
Pinpoint Impersonate - Gilad Lavian's Blog

Gilad Lavian's Blog

In Development

Pinpoint Impersonate

In common web developing, I use impersonation to identify against some services, and some other applications like SQL server with my windows credentials.

 

The usual way is to add to the web.config this line: <identity impersonate="true"/>

This is best practice for most cases in web developing, but the problem here is, it will effect on all identification procedures we have in the application.

 

Pinpoint Impersonation

Suppose I don't want it to effect all my identification procedures, and I want to impersonate just for the specific procedure in my code and then undo the impersonation action, here is a nice way for pinpoint impersonation:

public static void Impersonate()
{
    IPrincipal principal = HttpContext.Current.User; 
    WindowsIdentity identity = (WindowsIdentity)principal.Identity; 
    identity.Impersonate(); 
    string userName = identity.Name;
}

public static void UndoImpersonate()
{
    IPrincipal principal = HttpContext.Current.User;
    WindowsIdentity identity = (WindowsIdentity)principal.Identity;
    identity.Impersonate().Undo();
    string userName = identity.Name;
}

תוכן התגובה

Gil Fink כתב/ה:

Hi Gilad,

In the Undo method you call the Impersonate method again to undo the impersonation. You should save the WindowsImpersonationContext that is returned in the Impersonate method and then use it in the Undo method to Undo the impersonation.

# May 5, 2008 9:58 PM

Gilad Lavian כתב/ה:

Thanks gil, good point here.

# May 6, 2008 10:56 AM

Justin-Josef Angel [MVP] כתב/ה:

Tapuz trackback from www.tapuz.co.il/.../Viewmsg.asp

# May 6, 2008 2:56 PM
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 7 and 3 and type the answer here:


Enter the numbers above: