Create a new page in your App_Code folder and paste the following code there:
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class CustomImpersonation
{
    #region Fields
    private IntPtr tokenHandle = new IntPtr(0);
    private IntPtr dupeTokenHandle = new IntPtr(0);
    private WindowsImpersonationContext impersonationContext;
    #endregion
    #region Ctor
    public CustomImpersonation() : base() { }
    #endregion
    #region Extern Public Methods
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
    //[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    //private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
    //    int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr* Arguments);
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
    #endregion
    #region Public Methods
    /// 
    /// Pass user account you wish to impersonate.
    ///  
    /// 
/// 
/// 
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public void Impersonate(string userName, string password, string domainName)
   {
        try
       {
            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;
            this.tokenHandle = IntPtr.Zero;
            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(userName, domainName, password,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);
           if (false == returnValue)
           {
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
           }
           // Use the token handle returned by LogonUser.
            WindowsIdentity newId = new WindowsIdentity(tokenHandle);
            this.impersonationContext = newId.Impersonate();
        }
        catch (Exception ex)
      {
            throw ex;
        }
    }
    /// 
    /// Stop impersonating the user.
    ///  
    /// 
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public void Undo()
   {
        this.impersonationContext.Undo();
        // Free the tokens.
        if (this.tokenHandle != IntPtr.Zero)
            CloseHandle(this.tokenHandle);
    }
    #endregion
}
//create new instance
CustomImpersonation myImpersonation = new CustomImpersonation();
try
{
    // start impersonation                
    myImpersonation.Impersonate("username","password","domain");
    //put the code you want to run while impersonating the user account here
} catch(Exception ex) {
 throw ex;
} finally {
 myImpersonation.Undo();
}
No comments:
Post a Comment