<November 2018>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789
Neat way to programmatically impersonate in c#

//code executing under default account
using (Impersonator impersonator = new Impersonator("myDomain", "myUsername", "myPassword"))
{
    // code executing under myUsername account
}
//code executing under default account
If you need to execute few methods under different account than the one your code is currently executing under (account shown in User Name column in Task Manager for your process) all you need to do is to surround them with above code and include below class into your project.


  public class Impersonator : IDisposable
    {
        private WindowsImpersonationContext _impersonatedUser = null;
        private IntPtr _userHandle;

        public Impersonator(string userDomain, string username, string password)
        {
            this._userHandle = new IntPtr(0);
            bool returnValue = LogonUser(username, userDomain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref this._userHandle);
            if (!returnValue)
            {
                throw new ApplicationException("Could not impersonate user");
            }
            WindowsIdentity newId = new WindowsIdentity(this._userHandle);
            this._impersonatedUser = newId.Impersonate();
        }

        #region IDisposable Members
        public void Dispose()
        {
            if (this._impersonatedUser != null)
            {
                this._impersonatedUser.Undo();
                CloseHandle(_userHandle);
            }
        }
        #endregion

        #region Interop imports/constants
        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
    }
Above code is from here.
No Comments

Title
Author
Comment
Anti Bot Image   
  

Comments

Name
E-Mail@
(optional; never shown publicly; for notifications from this thread)
Comment
Anti Bot Image