using
System;
using
System.Web;
using
System.Web.Security;
using
System.Security.Principal;
using
System.Runtime.InteropServices;
namespace
tu.Web.Security.Impersonation{
public class ImpersonateUser : IDisposable{
#region
"datamember"
protected const int LOGON32_LOGON_INTERACTIVE = 2;
protected const int LOGON32_PROVIDER_DEFAULT = 0;
private WindowsImpersonationContext m_impersonationContext;
#endregion
"
#region
"properties"
public WindowsImpersonationContext ImpersonationContext{
get{
return this.m_impersonationContext;
}
}
#endregion
#region
"ctor"
public ImpersonateUser(string username, string domain, string pwd){
if(this.ImpersonateValidUser(username, domain, pwd)) {
}
else {
throw new ApplicationException("Error during impersonating the current user.");
}
}
#endregion
#region
"dtor"
public virtual void Dispose(){
this.UndoImpersonation();
}
#endregion
#region
"Declaration of ApiFunctions"
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
public static extern int LogonUser(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
public extern static int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
#endregion
#region
"helper functions"
private bool ImpersonateValidUser(string userName, string domain, string password) {
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0) {
if(DuplicateToken(token, 2, ref tokenDuplicate) != 0) {
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
this.m_impersonationContext = tempWindowsIdentity.Impersonate();
if (this.m_impersonationContext != null){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
else{
return false;
}
}
public void UndoImpersonation() {
this.m_impersonationContext.Undo();
}
#endregion
}
}