using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.ComponentModel;
namespace Mullivan.Security
{
public static class CredentialImpersonate
{
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;
public static WindowsImpersonationContext Impersonate(string domain, string userName, string password)
{
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
try
{
if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token))
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
return new WindowsIdentity(tokenDuplicate).Impersonate();
}
else
throw new Win32Exception(Marshal.GetLastWin32Error(), "DuplicateToken Failed");
}
else
throw new Win32Exception(Marshal.GetLastWin32Error(), "LogonUser Failed");
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
}
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(IntPtr handle);
}
}