Skip to content

Instantly share code, notes, and snippets.

@bungard
Created March 3, 2015 19:26
Show Gist options
  • Save bungard/4f9bab1b2199599cb453 to your computer and use it in GitHub Desktop.
Save bungard/4f9bab1b2199599cb453 to your computer and use it in GitHub Desktop.
//As pulled from: http://support.microsoft.com/kb/306158
static private bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment