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;
}