CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Programmatic Impersonation Utilities

256 Views
Copy Code Show/Hide Line Numbers
public class SecurityUtils
{
 
    const int LOGON32_LOGON_INTERACTIVE = 2;
    const int LOGON32_LOGON_NETWORK = 3;
    const int LOGON32_LOGON_BATCH = 4;
    const int LOGON32_LOGON_SERVICE = 5;
    const int LOGON32_LOGON_UNLOCK = 7;
    const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
    const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
    const int LOGON32_PROVIDER_DEFAULT = 0;
 
    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern int LogonUser(
        string lpszUsername,
        string lpszDomain,
        string lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        out IntPtr phToken
        );
 
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern int CloseHandle(IntPtr hObject);
 
    public static WindowsImpersonationContext ImpersonateUser(string username, string password, string domain)
    {
        IntPtr token = IntPtr.Zero;
        try
        {                
            int TResult = LogonUser(username, domain, password,
                                    LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT,
                                    out token);
 
            WindowsImpersonationContext context = null;
            context = WindowsIdentity.Impersonate(token);
            CloseHandle(token);
 
            return context;
        }
        catch
        {
            return null;
        }
        finally
        {
            if (token != IntPtr.Zero)
                CloseHandle(token);
        }
    }
 
    public static void RevertImpersonation(WindowsImpersonationContext context)
    {
        context.Undo();
        context.Dispose();
    }
}
by Rick Strahl
  September 23, 2009 @ 5:34pm
Tags:

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate