private void ImpersonateUser(string userName, string password, string domainName)
{
const int LOGON32_TYPE_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_WINNT50 = 3;
const int SecurityImpersonation = 2;
tokenHandle = IntPtr.Zero;
dupeTokenHandle = IntPtr.Zero;
// Call LogonUser to obtain a handle to an access token.
// If domain joined
bool returnValue = LogonUser(userName, domainName, password, LOGON32_TYPE_NEW_CREDENTIALS,
LOGON32_PROVIDER_WINNT50, ref tokenHandle);
if (!returnValue)
{
int ret = Marshal.GetLastWin32Error();
const int errorCode = 0x5; //ERROR_ACCESS_DENIED
throw new System.ComponentModel.Win32Exception(errorCode);
}
returnValue = DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle);
if (!returnValue)
{
CloseHandle(tokenHandle);
//Exception thrown in trying to duplicate token.
return;
}
// The token that is passed to the following constructor must be a primary token in order to use it for impersonation.
WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
impersonatedUser = newId.Impersonate();
}