Skip to content

Instantly share code, notes, and snippets.

@JakeWharton
Created November 5, 2009 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JakeWharton/227121 to your computer and use it in GitHub Desktop.
Save JakeWharton/227121 to your computer and use it in GitHub Desktop.
Allows you to execute code under another user's privileges.
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