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
| public class Impersonator
{
[DllImport("advapi32", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr token);
[DllImport("advapi32", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(IntPtr handle);
private string _userName;
private string _password;
private string _domain;
private WindowsImpersonationContext _impContext;
public Impersonator(string userName, string domain, string password)
{
_userName = userName;
_password = password;
_domain = domain;
}
private WindowsIdentity Logon()
{
WindowsIdentity winIdentity = null;
try
{
IntPtr handle = new IntPtr(0);
bool logOnSuccess = false;
logOnSuccess = LogonUser(_userName, _domain, _password, 3, 0, out handle);
if (!logOnSuccess)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Exception("User logon failed. Error code : " + errorCode);
}
winIdentity = new WindowsIdentity(handle);
CloseHandle(handle);
}
catch{}
return winIdentity;
}
public void Impersonate()
{
try
{
_impContext = Logon().Impersonate();
}
catch { }
}
public void UndoImpersonate()
{
try
{
_impContext.Undo();
}
catch { }
}
} |
Partager