public bool Impersonate(string userName, string domain, string password)
{
var token = IntPtr.Zero;
var tokenDuplicate = IntPtr.Zero;
if(RevertToSelf())
{
if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out token))
{
if(DuplicateToken(token, 2, out tokenDuplicate) != 0)
{
var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
_impersonationContext = tempWindowsIdentity.Impersonate();
if(_impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if(token != IntPtr.Zero)
{
CloseHandle(token);
}
if(tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
return false;
}