You can use the following code to impersonate users:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public class Impersonator : IDisposable
{
#region API
[DllImport("advapi32.dll", SetLastError = true)]
private static extern int 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("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(IntPtr handle);
private const int LogonInteractive = 2;
private const int LogonDefaultProvider = 0;
#endregion
private WindowsImpersonationContext m_impersonationContext = null;
public Impersonator(string userName, string domainName, string password)
{
ImpersonateValidUser(userName, domainName, password);
}
public void Dispose()
{
UndoImpersonation();
}
private void ImpersonateValidUser(string userName, string domain, string password)
{
WindowsIdentity tempWindowsIdentity = null;
var token = IntPtr.Zero;
var tokenDuplicate = IntPtr.Zero;
try
{
if (RevertToSelf())
{
if (LogonUser(userName, domain, password, LogonInteractive, LogonDefaultProvider, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
m_impersonationContext = tempWindowsIdentity.Impersonate();
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
}
}
private void UndoImpersonation()
{
if (m_impersonationContext != null)
{
m_impersonationContext.Undo();
}
}
}
The way to use it is very easy:
using (var impersonator = new Impersonator("userName", "domainName", "password"))
{
// Place your code here
}
Hope this helps,
Miguel.