154

Is there a simple out of the box way to impersonate a user in .NET?

So far I've been using this class from code project for all my impersonation requirements.

Is there a better way to do it by using .NET Framework?

I have a user credential set, (username, password, domain name) which represents the identity I need to impersonate.

Ralph Willgoss
  • 11,750
  • 4
  • 64
  • 67
ashwnacharya
  • 14,601
  • 23
  • 89
  • 112

7 Answers7

334

"Impersonation" in the .NET space generally means running code under a specific user account. It is a somewhat separate concept than getting access to that user account via a username and password, although these two ideas pair together frequently.

Impersonation

The APIs for impersonation are provided in .NET via the System.Security.Principal namespace:

  • Newer code should generally use WindowsIdentity.RunImpersonated, which accepts a handle to the token of the user account, and then either an Action or Func<T> for the code to execute.

    WindowsIdentity.RunImpersonated(userHandle, () =>
    {
        // do whatever you want as this user.
    });
    

    or

    var result = WindowsIdentity.RunImpersonated(userHandle, () =>
    {
        // do whatever you want as this user.
        return result;
    });
    

    There's also WindowsIdentity.RunImpersonatedAsync for async tasks, available on .NET 5+, or older versions if you pull in the System.Security.Principal.Windows Nuget package.

    await WindowsIdentity.RunImpersonatedAsync(userHandle, async () =>
    {
        // do whatever you want as this user.
    });
    

    or

    var result = await WindowsIdentity.RunImpersonated(userHandle, async () =>
    {
        // do whatever you want as this user.
        return result;
    });
    
  • Older code used the WindowsIdentity.Impersonate method to retrieve a WindowsImpersonationContext object. This object implements IDisposable, so generally should be called from a using block.

    using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(userHandle))
    {
        // do whatever you want as this user.
    }
    

    While this API still exists in .NET Framework, it should generally be avoided.

Accessing the User Account

The API for using a username and password to gain access to a user account in Windows is LogonUser - which is a Win32 native API. There is not currently a built-in managed .NET API for calling it.

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

This is the basic call definition, however there is a lot more to consider to actually using it in production:

  • Obtaining a handle with the "safe" access pattern.
  • Closing the native handles appropriately
  • Code access security (CAS) trust levels (in .NET Framework only)
  • Passing SecureString when you can collect one safely via user keystrokes.

Instead of writing that code yourself, consider using my SimpleImpersonation library, which provides a managed wrapper around the LogonUser API to get a user handle:

using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
using SimpleImpersonation;

var credentials = new UserCredentials(domain, username, password);
using SafeAccessTokenHandle userHandle = credentials.LogonUser(LogonType.Interactive);  // or another LogonType

You can now use that userHandle with any of the methods mentioned in the first section above. This is the preferred API as of version 4.0.0 of the SimpleImpersonation library. See the project readme for more details.

Remote Computer Access

It's important to recognize that impersonation is a local machine concept. One cannot impersonate using a user that is only known to a remote machine. If you want to access resources on a remote computer, the local machine and the remote machine must be attached to the same domain, or there needs to be a trust relationship between the domains of the two machines. If either computer is domainless, you cannot use LogonUser or SimpleImpersonation to connect to that machine.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • 16
    This is very similar to the code available at http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx but it's incredibly great to see it all listed here. Straightforward and easy to incorporate into my solution. Thanks much for doing all the hard work! – McArthey Feb 13 '12 at 20:17
  • 1
    Thanks for posting this. However, in the using statement I tried this line of code System.Security.Principal.WindowsIdentity.GetCurrent().Name and the result was just the username I logged in with not the one I passed into the Impersonation contructor. – Chris Apr 22 '13 at 17:12
  • 3
    @Chris - You would need to use one of the other login types. Type 9 only provides impersonation on outbound network credentials. I tested types 2, 3 & 8 from a WinForms app, and they do properly update the current principal. One would assume types 4 and 5 do also, for service or batch applications. See the link I referenced in the post. – Matt Johnson-Pint Apr 22 '13 at 17:30
  • You Rock! This is only the impersonation that worked for me. This is better than the msdn itself (sadly!): http://support.microsoft.com/kb/306158#3 – user1019042 Jul 18 '13 at 13:38
  • In .NET 4.0 app, somehow impersonation persists after using statement. How that can be possible? – synergetic Sep 11 '13 at 10:52
  • 1
    @synergetic - It depends what you are doing with it. For example, if you are accessing a database, then the connection may retain the impersonated user context due to the [issue discussed here](http://stackoverflow.com/q/18198291/634824). If it's something else, then ask a new question please - or [raise an issue here](https://github.com/mj1856/SimpleImpersonation/issues) if it's specifically with my library. Thanks. – Matt Johnson-Pint Sep 11 '13 at 14:34
  • @MattJohnson: Many thanks for this useful code. I'm trying to use it but I found a problem with the call to `WindowsIdentity.Impersonate()`, as I explain here: http://stackoverflow.com/questions/22427500/error-no-token-after-call-to-windowsidentity-impersonate. Any ideas? Thanks. – CesarGon Mar 15 '14 at 17:50
  • @MattJohnson -- I'm trying out this code, but I've noticed that if I call `System.Diagnostics.Debug.Print(Environment.UserName)` from within the `using (new Impersonation("MyDomain", "MyUser", "MyPassword"))` block, it displays the name of the logged on user instead of the impersonated user. Other things are working as expected from within this block (e.g. network access to a resource that the logged on user doesn't have access to but the impersonated user does). – rory.ap Apr 25 '14 at 17:38
  • @roryap - That's the behavior of `LOGON32_LOGON_NEW_CREDENTIALS`. You might try one of the other logon types. Also, it's cleaner if you use my nuget package referenced in the update. – Matt Johnson-Pint Apr 25 '14 at 18:46
  • This doesn't work, if the originating user is the SYSTEM user. It impersonates at a local level, but once I try doing things that require permissions (Remote Registry reading, for example) it fails with: Attempted to perform an unauthorized operation – bill Jun 03 '14 at 20:29
  • @bill - Please read the MSDN docs for `LogonUser`. You may need to specify a specific logon type. http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184.aspx – Matt Johnson-Pint Jun 04 '14 at 00:38
  • I understand that. What I did, was exposed the logon type to the public method so the syntax is: using (new Impersonation(domain, username, password, logonType)) I then made 8 calls (logon types 2-9) to this and tested each one for its results. Logon type 7 and 8 both come back as The user I invoked, but cannot do anything that requires permissions. – bill Jun 04 '14 at 04:02
  • Sorry, I don't have any further suggestions. Perhaps you could ask a new question about the behavior of LogonUser when run from the system account. A Google/Bing search shows some other questions along those lines, but I didn't see anything definitive. – Matt Johnson-Pint Jun 04 '14 at 06:16
  • This worked for me, but I had to give the impersonated user permissions to the SHARE (Right click folder, Properties - > Sharing -> Advanced Sharing - > Permissions - > Add) as well as the specific folder where I was saving things. – scw Jul 03 '14 at 16:36
  • @bill I would assume that the local SYSTEM user has no rights outside the local box, so I would expect any and all external access to fail. – Joshua Drake Sep 03 '14 at 18:51
  • Dispose() should call _context.Undo(). – Sophit Oct 02 '14 at 20:31
  • 2
    @Sophit - [It already does](http://referencesource.microsoft.com/#mscorlib/system/security/principal/windowsimpersonationcontext.cs#134). – Matt Johnson-Pint Oct 02 '14 at 20:34
  • @MattJohnson No, it does not. _context.Dispose() may or may not revert impersonation, but it's not documented that it does so. – Sophit Oct 02 '14 at 20:48
  • 4
    @Sophit - The [reference source code here](http://referencesource.microsoft.com/#mscorlib/system/security/principal/windowsimpersonationcontext.cs#134) clearly shows `Undo` being called during disposal. – Matt Johnson-Pint Oct 02 '14 at 21:35
  • @MattJohnson That's an offsite reference and doesn't help anyone reading the code here. – Sophit Oct 03 '14 at 19:27
  • Adding the following FLAG fixed my issue thanks for the info! LOGON32_LOGON_NEW_CREDENTIALS was needed for domain auth. – bigamil Dec 13 '16 at 23:20
  • logon type 9 (new credentials) is is a lifesaver, never would have found it – smirkingman Feb 01 '17 at 12:38
  • I get the error of System.ArgumentException: 'Username cannot contain \ or @ characters when domain is provided separately. (Parameter 'username')'. I have to include \ in he username so how to solve this issue.Below is my code: UserCredentials credentials = new UserCredentials("111.222.333.45", "ABC\Test.test", "Test@12"); var result = Impersonation.RunAsUser(credentials, LogonType.Interactive, () => { return System.IO.Directory.GetFiles(@"\\111.222.333.45\D$"); }); @Matt Johson-Print – Sabbu Mar 23 '22 at 19:10
  • @Sabbu - In your example, the domain parameter should be `"ABC"`, not `"111.222.333.45"`. Also, please don't tack on new questions as comments. Either [create a new question](https://stackoverflow.com/questions/ask), or [raise an issue on the github repo for the project](https://github.com/mattjohnsonpint/SimpleImpersonation/issues/new). Thanks. – Matt Johnson-Pint Mar 23 '22 at 19:52
  • @MattJohnson I had pass the domain parameter as you mentioned "ABC-COOLS.NCC.LOCAL" and get the same issue. Let me raise the issue on the github.Thanks – Sabbu Mar 23 '22 at 20:00
63

Here is some good overview of .NET impersonation concepts.

Basically you will be leveraging these classes that are out of the box in the .NET framework:

The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.

kͩeͣmͮpͥ ͩ
  • 7,783
  • 26
  • 40
Eric Schoonover
  • 47,184
  • 49
  • 157
  • 202
  • 4
    Just a note that impersonation is not the silver bullet and some APIs are simply not designed to work with impersonation. – Lex Li Mar 24 '14 at 06:14
  • That link from the Dutch programmer's blog was excellent. Much more intuitive approach to impersonation than the other techniques presented. – code4life Aug 22 '16 at 23:26
20

This is probably what you want:

using System.Security.Principal;
using(WindowsIdentity.GetCurrent().Impersonate())
{
     //your code goes here
}

But I really need more details to help you out. You could do impersonation with a config file (if you're trying to do this on a website), or through method decorators (attributes) if it's a WCF service, or through... you get the idea.

Also, if we're talking about impersonating a client that called a particular service (or web app), you need to configure the client correctly so that it passes the appropriate tokens.

Finally, if what you really want do is Delegation, you also need to setup AD correctly so that users and machines are trusted for delegation.

Edit:
Take a look here to see how to impersonate a different user, and for further documentation.

Esteban Araya
  • 29,284
  • 24
  • 107
  • 141
  • 2
    This code looks like it can impersonate only the Current windows Identity. Is there a way to get the WindowsIdentity object of another user? – ashwnacharya Sep 24 '08 at 04:07
  • The link in your edit (https://msdn.microsoft.com/en-us/library/chf6fbt4.aspx - go to **Examples** there) is really what I was looking for! – Matt Feb 02 '17 at 12:56
  • Wow! you guided me in the right direction, just a few words were needed to do the magic **impersonation with a config file** Thank you Esteban, saludos desde Peru – AjFmO Oct 07 '19 at 21:02
7

Here's my vb.net port of Matt Johnson's answer. I added an enum for the logon types. LOGON32_LOGON_INTERACTIVE was the first enum value that worked for sql server. My connection string was just trusted. No user name / password in the connection string.

  <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
  Public Class Impersonation
    Implements IDisposable

    Public Enum LogonTypes
      ''' <summary>
      ''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
      ''' by a terminal server, remote shell, or similar process.
      ''' This logon type has the additional expense of caching logon information for disconnected operations; 
      ''' therefore, it is inappropriate for some client/server applications,
      ''' such as a mail server.
      ''' </summary>
      LOGON32_LOGON_INTERACTIVE = 2

      ''' <summary>
      ''' This logon type is intended for high performance servers to authenticate plaintext passwords.
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_NETWORK = 3

      ''' <summary>
      ''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without 
      ''' their direct intervention. This type is also for higher performance servers that process many plaintext
      ''' authentication attempts at a time, such as mail or Web servers. 
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_BATCH = 4

      ''' <summary>
      ''' Indicates a service-type logon. The account provided must have the service privilege enabled. 
      ''' </summary>
      LOGON32_LOGON_SERVICE = 5

      ''' <summary>
      ''' This logon type is for GINA DLLs that log on users who will be interactively using the computer. 
      ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. 
      ''' </summary>
      LOGON32_LOGON_UNLOCK = 7

      ''' <summary>
      ''' This logon type preserves the name and password in the authentication package, which allows the server to make 
      ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials 
      ''' from a client, call LogonUser, verify that the user can access the system across the network, and still 
      ''' communicate with other servers.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8

      ''' <summary>
      ''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
      ''' The new logon session has the same local identifier but uses different credentials for other network connections. 
      ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
    End Function

    Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
      Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
      If Not ok Then
        Dim errorCode = Marshal.GetLastWin32Error()
        Throw New ApplicationException(String.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode))
      End If

      WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
    End Sub

    Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
    Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext

    Public Sub Dispose() Implements System.IDisposable.Dispose
      Me.WindowsImpersonationContext.Dispose()
      Me._SafeTokenHandle.Dispose()
    End Sub

    Public NotInheritable Class SafeTokenHandle
      Inherits SafeHandleZeroOrMinusOneIsInvalid

      <DllImport("kernel32.dll")> _
      <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
      <SuppressUnmanagedCodeSecurity()> _
      Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
      End Function

      Public Sub New()
        MyBase.New(True)
      End Sub

      Protected Overrides Function ReleaseHandle() As Boolean
        Return CloseHandle(handle)
      End Function
    End Class

  End Class

You need to Use with a Using statement to contain some code to run impersonated.

toddmo
  • 20,682
  • 14
  • 97
  • 107
6

View more detail from my previous answer I have created an nuget package Nuget

Code on Github

sample : you can use :

string login = "";
string domain = "";
string password = "";

using (UserImpersonation user = new UserImpersonation(login, domain, password))
{
   if (user.ImpersonateValidUser())
   {
       File.WriteAllText("test.txt", "your text");
       Console.WriteLine("File writed");
   }
   else
   {
       Console.WriteLine("User not connected");
   }
}

View the full code :

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;


/// <summary>
/// Object to change the user authticated
/// </summary>
public class UserImpersonation : IDisposable
{
    /// <summary>
    /// Logon method (check athetification) from advapi32.dll
    /// </summary>
    /// <param name="lpszUserName"></param>
    /// <param name="lpszDomain"></param>
    /// <param name="lpszPassword"></param>
    /// <param name="dwLogonType"></param>
    /// <param name="dwLogonProvider"></param>
    /// <param name="phToken"></param>
    /// <returns></returns>
    [DllImport("advapi32.dll")]
    private static extern bool LogonUser(String lpszUserName,
        String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);

    /// <summary>
    /// Close
    /// </summary>
    /// <param name="handle"></param>
    /// <returns></returns>
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);

    private WindowsImpersonationContext _windowsImpersonationContext;
    private IntPtr _tokenHandle;
    private string _userName;
    private string _domain;
    private string _passWord;

    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_LOGON_INTERACTIVE = 2;

    /// <summary>
    /// Initialize a UserImpersonation
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="domain"></param>
    /// <param name="passWord"></param>
    public UserImpersonation(string userName, string domain, string passWord)
    {
        _userName = userName;
        _domain = domain;
        _passWord = passWord;
    }

    /// <summary>
    /// Valiate the user inforamtion
    /// </summary>
    /// <returns></returns>
    public bool ImpersonateValidUser()
    {
        bool returnValue = LogonUser(_userName, _domain, _passWord,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref _tokenHandle);

        if (false == returnValue)
        {
            return false;
        }

        WindowsIdentity newId = new WindowsIdentity(_tokenHandle);
        _windowsImpersonationContext = newId.Impersonate();
        return true;
    }

    #region IDisposable Members

    /// <summary>
    /// Dispose the UserImpersonation connection
    /// </summary>
    public void Dispose()
    {
        if (_windowsImpersonationContext != null)
            _windowsImpersonationContext.Undo();
        if (_tokenHandle != IntPtr.Zero)
            CloseHandle(_tokenHandle);
    }

    #endregion
}
DanB
  • 2,022
  • 1
  • 12
  • 24
Cedric Michel
  • 502
  • 5
  • 13
4

I'm aware that I'm quite late for the party, but I consider that the library from Phillip Allan-Harding, it's the best one for this case and similar ones.

You only need a small piece of code like this one:

private const string LOGIN = "mamy";
private const string DOMAIN = "mongo";
private const string PASSWORD = "HelloMongo2017";

private void DBConnection()
{
    using (Impersonator user = new Impersonator(LOGIN, DOMAIN, PASSWORD, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50))
    {
    }
}

And add his class:

.NET (C#) Impersonation with Network Credentials

My example can be used if you require the impersonated login to have network credentials, but it has more options.

Federico Navarrete
  • 3,069
  • 5
  • 41
  • 76
0

You can use this solution. (Use nuget package) The source code is available on : Github: https://github.com/michelcedric/UserImpersonation

More detail https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/

Cedric Michel
  • 502
  • 5
  • 13