Created
November 5, 2009 15:26
-
-
Save JakeWharton/227121 to your computer and use it in GitHub Desktop.
Allows you to execute code under another user's privileges.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
using System.Security.Principal; | |
namespace JakeWharton | |
{ | |
public class Impersonator : IDisposable | |
{ | |
private WindowsImpersonationContext ImpersonatedUser = null; | |
private IntPtr UserHandle; | |
public Impersonator(string Username, string Domain, string Password) | |
{ | |
this.UserHandle = new IntPtr(0); | |
if (!Impersonator.LogonUser(Username, Domain, Password, Impersonator.LOGON32_LOGON_INTERACTIVE, | |
Impersonator.LOGON32_PROVIDER_DEFAULT, ref this.UserHandle)) | |
{ | |
throw new ApplicationException(string.Format("Could not impersonate user \"{0}\\{1}\".", Domain, Username)); | |
} | |
this.ImpersonatedUser = (new WindowsIdentity(this.UserHandle)).Impersonate(); | |
} | |
#region IDisposable Members | |
public void Dispose() | |
{ | |
if (this.ImpersonatedUser != null) | |
{ | |
this.ImpersonatedUser.Undo(); | |
Impersonator.CloseHandle(UserHandle); | |
} | |
} | |
#endregion | |
#region Interoperability | |
public const int LOGON32_LOGON_INTERACTIVE = 2; | |
public const int LOGON32_LOGON_SERVICE = 3; | |
public const int LOGON32_PROVIDER_DEFAULT = 0; | |
[DllImport("advapi32.dll", CharSet = CharSet.Auto)] | |
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); | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment