|
Introduction
The term "Impersonation" in a programming context refers to a technique that executes the code under another user context than the user who originally started an application, i.e. the user context is temporarily changed once or multiple times during the execution of an application.
The reason for doing this is to perform tasks that the current user context of an application is not allowed to do. Of course you could grant the user executing an application more privileges, but usually this is a bad idea (due to security constraints) or impossible (e.g. if you don't have full administrative access to a machine to do so).
This article presents an easy-to-use class to impersonate a user. While writing this, I found out that Marc Merrit had written an article ("Windows Impersonation using C#") that uses the same Microsoft knowledge base code (from Q306158) that I have used. The code presented in my article differs in the fact that you could use it inside a using-block to safely release resources and that I use slightly more exceptions to report errors. But from a first look, both his and my article do the same job, so it's up to you to decide what to do.
(For the latest changes, please see the History section below).
Background
I wrote the Impersonator class because of a need to write a web page with ASP.NET to make a server reboot. In order to do this, I needed to impersonate the part of my code that does the actual reboot.
The constructor of the class internally calls the Windows function LogonUser through P/Invoke. Please see the MSDN documentation of the function for a full description of all three parameters (username, domain, password) to the constructor.
Please note: The user context that initiates the impersonation (i.e. not the user context to which it is switched to) needs to have the "Act as part of operating system" privilege set.
Using the code
To use the code, you simply construct the Impersonator class and pass the username, the domain and the password to the constructor. If you place an instance of the class inside a using-block, you need no further steps.
The following is a schematic example of how to use the class: ...
using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
...
<code that executes under the new context>
...
}
...
An example project demonstrating the technique is included in the download of this article (please look at the "Program.cs" for the main demonstration source file). Also the complete source code of the class is included inside the source file "Impersonator.cs".
To include the Impersonator class into your project, simply copy and add the source file "Impersonator.cs" to your project, so that it gets compiled with your project.
Conclusion
In this article, I've shown you a small class to quickly and easily impersonate a part of your code to run under another user context. Hopefully you'll find this class useful.
For questions, comments and remarks, please use the commenting section at the bottom of this article.
References
In addition to the links in the article, the following references might be of interest:
- Google search for "Windows Impersonation"
History
- 2005-04-11: Created first version of article.
| You must Sign In to use this message board. |
|
| | Msgs 1 to 25 of 82 (Total in Forum: 82) (Refresh) | FirstPrevNext |
|
 |
|
|
If i have a call to OpenFileDialog within a using Impersonator block the OpenFileDialog browsing seems to have the same permissions as my own login rather than the impersonated login.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
As a preview excerpt from an internal class library (which I plan to release in the near future), the following reply to this message contains a much enhanced version.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
namespace Zeta.EnterpriseLibrary.Tools { #region Using directives. // ----------------------------------------------------------------------
using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Security.Principal;
// ---------------------------------------------------------------------- #endregion
/////////////////////////////////////////////////////////////////////////
/// <summary> /// Impersonation of a user. Allows to execute code under another /// user context. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <remarks> /// This class is based on the information in the Microsoft knowledge base /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158 /// /// Encapsulate an instance into a using-directive like e.g.: /// /// ... /// using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) ) /// { /// ... /// [code that executes under the new context] /// ... /// } /// ... /// </remarks> public class Impersonator : IDisposable { #region Public methods. // ------------------------------------------------------------------
/// <summary> /// Initializes a new instance of the <see cref="Impersonator"/> class. /// </summary> public Impersonator() { }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="profileBehaviour">The profile behaviour.</param> public Impersonator( string userName, string domainName, string password, ProfileBehaviour profileBehaviour ) { ImpersonateValidUser( userName, domainName, password, LoginType.Interactive, profileBehaviour ); }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loginType">The login type.</param> /// <param name="profileBehaviour">The profile behaviour.</param> public Impersonator( string userName, string domainName, string password, LoginType loginType, ProfileBehaviour profileBehaviour ) { ImpersonateValidUser( userName, domainName, password, loginType, profileBehaviour ); }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="profileBehaviour">The profile behaviour.</param> public Impersonator( string userName, string domainName, SecureString password, ProfileBehaviour profileBehaviour ) { ImpersonateValidUser( userName, domainName, password, LoginType.Interactive, profileBehaviour ); }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loginType">The login type.</param> /// <param name="profileBehaviour">The profile behaviour.</param> public Impersonator( string userName, string domainName, SecureString password, LoginType loginType, ProfileBehaviour profileBehaviour ) { ImpersonateValidUser( userName, domainName, password, loginType, profileBehaviour ); }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> public Impersonator( string userName, string domainName, string password ) { ImpersonateValidUser( userName, domainName, password, LoginType.Interactive, ProfileBehaviour.DontLoad ); }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loginType">The login type.</param> public Impersonator( string userName, string domainName, string password, LoginType loginType ) { ImpersonateValidUser( userName, domainName, password, loginType, ProfileBehaviour.DontLoad ); }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> public Impersonator( string userName, string domainName, SecureString password ) { ImpersonateValidUser( userName, domainName, password, LoginType.Interactive, ProfileBehaviour.DontLoad ); }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loginType">The login type.</param> public Impersonator( string userName, string domainName, SecureString password, LoginType loginType ) { ImpersonateValidUser( userName, domainName, password, loginType, ProfileBehaviour.DontLoad ); }
/// <summary> /// Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="profileBehaviour">The profile behaviour.</param> public void Impersonate( string userName, string domainName, string password, ProfileBehaviour profileBehaviour ) { ImpersonateValidUser( userName, domainName, password, LoginType.Interactive, profileBehaviour ); }
/// <summary> /// Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loginType">The login type.</param> /// <param name="profileBehaviour">The profile behaviour.</param> public void Impersonate( string userName, string domainName, string password, LoginType loginType, ProfileBehaviour profileBehaviour ) { ImpersonateValidUser( userName, domainName, password, loginType, profileBehaviour ); }
/// <summary> /// Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="profileBehaviour">The profile behaviour.</param> public void Impersonate( string userName, string domainName, SecureString password, ProfileBehaviour profileBehaviour ) { ImpersonateValidUser( userName, domainName, password, LoginType.Interactive, profileBehaviour ); }
/// <summary> /// Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loginType">The login type.</param> /// <param name="profileBehaviour">The profile behaviour.</param> public void Impersonate( string userName, string domainName, SecureString password, LoginType loginType, ProfileBehaviour profileBehaviour ) { ImpersonateValidUser( userName, domainName, password, loginType, profileBehaviour ); }
/// <summary> /// Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> public void Impersonate( string userName, string domainName, string password ) { ImpersonateValidUser( userName, domainName, password, LoginType.Interactive, ProfileBehaviour.DontLoad ); }
/// <summary> /// Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loginType">The login type.</param> public void Impersonate( string userName, string domainName, string password, LoginType loginType ) { ImpersonateValidUser( userName, domainName, password, loginType, ProfileBehaviour.DontLoad ); }
/// <summary> /// Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> public void Impersonate( string userName, string domainName, SecureString password ) { ImpersonateValidUser( userName, domainName, password, LoginType.Interactive, ProfileBehaviour.DontLoad ); }
/// <summary> /// Starts the impersonation with the given credentials. /// The account that instantiates the Impersonator class /// needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName">The name of the user to act as.</param> /// <param name="domainName">The domain name of the user to act as.</param> /// <param name="password">The password of the user to act as.</param> /// <param name="loginType">The login type.</param> public void Impersonate( string userName, string domainName, SecureString password, LoginType loginType ) { ImpersonateValidUser( userName, domainName, password, loginType, ProfileBehaviour.DontLoad ); }
/// <summary> /// Undoes the impersonation. Safe to call even if not yet /// impersonized. /// </summary> public void Undo() { UndoImpersonation(); }
// ------------------------------------------------------------------ #endregion
#region IDisposable member. // ------------------------------------------------------------------
/// <summary> /// Performs application-defined tasks associated with freeing, /// releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { UndoImpersonation(); GC.SuppressFinalize( this ); }
/// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="Impersonator"/> is reclaimed by garbage collection. /// </summary> ~Impersonator() { UndoImpersonation(); }
// ------------------------------------------------------------------ #endregion
#region P/Invoke. // ------------------------------------------------------------------
/// <summary> /// Logons the user. /// </summary> /// <param name="lpszUserName">Name of the LPSZ user.</param> /// <param name="lpszDomain">The LPSZ domain.</param> /// <param name="lpszPassword">The LPSZ password.</param> /// <param name="dwLogonType">Type of the dw logon.</param> /// <param name="dwLogonProvider">The dw logon provider.</param> /// <param name="phToken">The ph token.</param> /// <returns></returns> [DllImport( @"advapi32.dll", CharSet = CharSet.Auto, SetLastError = true )] private static extern int LogonUser( string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken );
/// <summary> /// Logons the user2. /// </summary> /// <param name="lpszUserName">Name of the LPSZ user.</param> /// <param name="lpszDomain">The LPSZ domain.</param> /// <param name="Password">The password.</param> /// <param name="dwLogonType">Type of the dw logon.</param> /// <param name="dwLogonProvider">The dw logon provider.</param> /// <param name="phToken">The ph token.</param> /// <returns></returns> [DllImport( @"advapi32.dll", EntryPoint = @"LogonUser", CharSet = CharSet.Unicode, SetLastError = true )] private static extern int LogonUser2( string lpszUserName, string lpszDomain, IntPtr Password, int dwLogonType, int dwLogonProvider, ref IntPtr phToken );
/// <summary> /// Duplicates the token. /// </summary> /// <param name="hToken">The h token.</param> /// <param name="impersonationLevel">The impersonation level.</param> /// <param name="hNewToken">The h new token.</param> /// <returns></returns> [DllImport( @"advapi32.dll", CharSet = CharSet.Auto, SetLastError = true )] private static extern int DuplicateToken( IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken );
/// <summary> /// Reverts to self. /// </summary> /// <returns></returns> [DllImport( @"advapi32.dll", CharSet = CharSet.Auto, SetLastError = true )] private static extern bool RevertToSelf();
/// <summary> /// Closes the handle. /// </summary> /// <param name="handle">The handle.</param> /// <returns></returns> [DllImport( @"kernel32.dll", CharSet = CharSet.Auto, SetLastError = true )] private static extern bool CloseHandle( IntPtr handle );
/// <summary> /// /// </summary> private const int LOGON32_PROVIDER_DEFAULT = 0;
[DllImport( @"userenv.dll", SetLastError = true, CharSet = CharSet.Auto )] private static extern bool LoadUserProfile( IntPtr hToken, ref PROFILEINFO lpProfileInfo );
[DllImport( @"userenv.dll", SetLastError = true, CharSet = CharSet.Auto )] private static extern bool UnloadUserProfile( IntPtr hToken, IntPtr hProfile );
[StructLayout( LayoutKind.Sequential )] private struct PROFILEINFO { public int dwSize; public int dwFlags; [MarshalAs( UnmanagedType.LPTStr )] public String lpUserName; [MarshalAs( UnmanagedType.LPTStr )] public String lpProfilePath; [MarshalAs( UnmanagedType.LPTStr )] public String lpDefaultPath; [MarshalAs( UnmanagedType.LPTStr )] public String lpServerName; [MarshalAs( UnmanagedType.LPTStr )] public String lpPolicyPath; public IntPtr hProfile; }
// ------------------------------------------------------------------ #endregion
#region Private methods. // ------------------------------------------------------------------
/// <summary> /// Does the actual impersonation. /// </summary> /// <param name="userName">The name of the user to act as.</param> | | | | | |