public static void impersonate(string userName, string password, string domain, Action action, int logonType = 2, int logonProvider = 0)
{
//elevate privileges before doing file copy to handle domain security
WindowsImpersonationContext context = null;
IntPtr userHandle = IntPtr.Zero;
try
{
Console.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);
// Call LogonUser to get a token for the user
bool loggedOn = NativeMethods.LogonUser(userName,
domain,
password,
logonType,
logonProvider,
ref userHandle);
if (!loggedOn)
{
Console.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
}
// Begin impersonating the user
context = WindowsIdentity.Impersonate(userHandle);
Console.WriteLine("windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);
//execute actions under impersonated user
action();
}
catch (Exception ex)
{
Console.WriteLine("Exception impersonating user: " + ex.Message);
}
finally
{
// Clean up
if (context != null)
{
context.Undo();
}
if (userHandle != IntPtr.Zero)
{
NativeMethods.CloseHandle(userHandle);
}
}
}