Skip to content

Instantly share code, notes, and snippets.

@cnayan
Last active October 23, 2020 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cnayan/4a9f592b50437d14fae2949439074803 to your computer and use it in GitHub Desktop.
Save cnayan/4a9f592b50437d14fae2949439074803 to your computer and use it in GitHub Desktop.
Impersonates as a user like "runas /netonly" feature.
// Check http://pinvoke.net/default.aspx/advapi32/LogonUser.html for Win32 functions and structures.
// Code based on answer on SO: https://stackoverflow.com/a/11672293/315151
// Impersonates as a user like "runas /netonly" feature.
public static void Impersonate(string userName, string password, string domain, Action action)
{
if (action == null)
{
return;
}
IntPtr token = IntPtr.Zero;
try
{
if (!Win32.RevertToSelf())
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (Win32.LogonUser(
userName,
domain,
password,
(int)LogOnType.LOGON32_LOGON_NEW_CREDENTIALS,
(int)LogOnProvider.LOGON32_PROVIDER_WINNT50,
ref token) == 0)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
IntPtr tokenDuplicate = IntPtr.Zero;
if (Win32.DuplicateToken(token, (int)SECURITY_IMPERSONATION_LEVEL.SecurityDelegation, ref tokenDuplicate) == 0)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
using var safeAccessTokenHandle = new SafeAccessTokenHandle(tokenDuplicate);
WindowsIdentity.RunImpersonated(safeAccessTokenHandle, action);
}
finally
{
if (token != IntPtr.Zero)
{
Win32.CloseHandle(token);
}
}
}
/*
Usage:
Impersonate(userName, password, domain, () =>
{
Your code
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment