Pages

Thursday, November 28, 2013

Validate user to on windows user account - Windows Identity Impersonation


IntPtr accessToken = IntPtr.Zero;
WindowsImpersonationContext impersonationContext = null;
try
{
 if (iFormsServiceUtil.ImpersonateValidUser(userName, domain, password, out impersonationContext))
 {
 }
}
catch (Exception ex)
{

}
finally
{
 if(impersonationContext != null)
  iFormsServiceUtil.UndoImpersonation(ref impersonationContext);
}


#region Windows Identity Impersonation

 private const int LOGON32_LOGON_INTERACTIVE = 2;
 private const int LOGON32_PROVIDER_DEFAULT = 0;

 //private WindowsImpersonationContext impersonationContext;
 [DllImport("advapi32.dll")]
 private static extern int LogonUserA(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);

 internal static bool ImpersonateValidUser(String userName, String domain, String password, out WindowsImpersonationContext impersonationContext)
 {
  WindowsIdentity tempWindowsIdentity;
  IntPtr token = IntPtr.Zero;
  IntPtr tokenDuplicate = IntPtr.Zero;
  impersonationContext = null;

  if (RevertToSelf())
  {
   if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
   {
    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
    {
     tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
     impersonationContext = tempWindowsIdentity.Impersonate();
     if (impersonationContext != null)
     {
      CloseHandle(token);
      CloseHandle(tokenDuplicate);
      return true;
     }
    }
   }
  }
  if (token != IntPtr.Zero)
   CloseHandle(token);
  if (tokenDuplicate != IntPtr.Zero)
   CloseHandle(tokenDuplicate);

  return false;
 }

 internal static void UndoImpersonation(ref WindowsImpersonationContext impersonationContext)
 {
  impersonationContext.Undo();
 }

#endregion

No comments:

Post a Comment