Language: C#
Programmatic Impersonation Utilities
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(); } }
Tags:
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

