Monday, February 7, 2011

User Impersonation using c# in Windows application

ImpersonateUser iU = new ImpersonateUser();
Login = iU.Impersonate(Global.Impersonate_DOMAIN, Global.Impersonate_UID, Global.Impersonate_PWD);





class ImpersonateUser
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);

private static IntPtr tokenHandle = new IntPtr(0);
private static WindowsImpersonationContext impersonatedUser;

[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public bool Impersonate(string domainName, string userName, string password)
{
bool returnValue;
const int LOGON32_PROVIDER_DEFAULT = 0;
// Passing this parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;

// ---- Step - 1
// Call LogonUser to obtain a handle to an access token.
returnValue = LogonUser(
userName,
domainName,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref tokenHandle); // tokenHandle - new security token

//commented for avoiding exception. Instead show message box with "wrong password"
//if (false == returnValue)
//{
// int ret = Marshal.GetLastWin32Error();
// Console.WriteLine("LogonUser call failed with error code : " + ret);
// throw new System.ComponentModel.Win32Exception(ret);
//}
if (returnValue == true)
{
// ---- Step - 2
WindowsIdentity newId = new WindowsIdentity(tokenHandle);

// ---- Step - 3
impersonatedUser = newId.Impersonate();
}
return returnValue;
}

// Stops impersonation
public void Undo()
{
impersonatedUser.Undo();
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
}

No comments:

Post a Comment