Last active
October 23, 2020 05:57
-
-
Save cnayan/4a9f592b50437d14fae2949439074803 to your computer and use it in GitHub Desktop.
Impersonates as a user like "runas /netonly" feature.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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