1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
public class Impersonation : IDisposable
{
public enum LogonType
{
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
LOGON32_LOGON_NEW_CREDENTIALS = 9
};
public enum LogonProvider
{
LOGON32_PROVIDER_DEFAULT = 0,
LOGON32_PROVIDER_WINNT35 = 1,
LOGON32_PROVIDER_WINNT40 = 2,
LOGON32_PROVIDER_WINNT50 = 3
};
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
private WindowsImpersonationContext _impersonationContext;
public Impersonation()
{
_impersonationContext = null;
}
public void Impersonate(
string userName,
string domainName,
string password,
LogonType logonType,
LogonProvider logonProvider)
{
IntPtr impersonationToken = IntPtr.Zero;
try
{
if (LogonUser(
userName,
domainName,
password,
(int)logonType,
(int)logonProvider,
out impersonationToken))
{
WindowsIdentity impersonationIdentity = new WindowsIdentity(impersonationToken);
_impersonationContext = impersonationIdentity.Impersonate();
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (impersonationToken != IntPtr.Zero)
{
CloseHandle(impersonationToken);
}
}
}
private void UndoImpersonation()
{
if (_impersonationContext != null)
{
_impersonationContext.Undo();
}
_impersonationContext = null;
}
public void Dispose()
{
UndoImpersonation();
}
} |
Partager