How do you do Impersonation in .NET?
Asked Answered
H

7

156

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.

Herzig answered 24/9, 2008 at 3:55 Comment(1)
Could you be more specific? There's tons of ways to do impersonation out of the box.Disembroil
P
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.

Perchloride answered 24/9, 2008 at 4:1 Comment(2)
Just a note that impersonation is not the silver bullet and some APIs are simply not designed to work with impersonation.Pep
That link from the Dutch programmer's blog was excellent. Much more intuitive approach to impersonation than the other techniques presented.Villein
H
339

"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.

Haakon answered 30/8, 2011 at 21:39 Comment(25)
This is very similar to the code available at msdn.microsoft.com/en-us/library/… 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!Kienan
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.Naldo
@Naldo - 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.Haakon
You Rock! This is only the impersonation that worked for me. This is better than the msdn itself (sadly!): support.microsoft.com/kb/306158#3Hijacker
In .NET 4.0 app, somehow impersonation persists after using statement. How that can be possible?Jedlicka
@Jedlicka - 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. If it's something else, then ask a new question please - or raise an issue here if it's specifically with my library. Thanks.Haakon
@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: #22428000. Any ideas? Thanks.Tl
@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).Juneberry
@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.Haakon
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 operationInstitute
@Institute - Please read the MSDN docs for LogonUser. You may need to specify a specific logon type. msdn.microsoft.com/en-us/library/windows/desktop/aa378184.aspxHaakon
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.Institute
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.Haakon
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.Yandell
@Institute 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.Herakleion
Dispose() should call _context.Undo().Manly
@Manly - It already does.Haakon
@MattJohnson No, it does not. _context.Dispose() may or may not revert impersonation, but it's not documented that it does so.Manly
@Manly - The reference source code here clearly shows Undo being called during disposal.Haakon
@MattJohnson That's an offsite reference and doesn't help anyone reading the code here.Manly
Adding the following FLAG fixed my issue thanks for the info! LOGON32_LOGON_NEW_CREDENTIALS was needed for domain auth.Desolation
logon type 9 (new credentials) is is a lifesaver, never would have found itBecky
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-PrintStamata
@Stamata - 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, or raise an issue on the github repo for the project. Thanks.Haakon
@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.ThanksStamata
P
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.

Perchloride answered 24/9, 2008 at 4:1 Comment(2)
Just a note that impersonation is not the silver bullet and some APIs are simply not designed to work with impersonation.Pep
That link from the Dutch programmer's blog was excellent. Much more intuitive approach to impersonation than the other techniques presented.Villein
D
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.

Disembroil answered 24/9, 2008 at 4:4 Comment(3)
This code looks like it can impersonate only the Current windows Identity. Is there a way to get the WindowsIdentity object of another user?Herzig
The link in your edit (msdn.microsoft.com/en-us/library/chf6fbt4.aspx - go to Examples there) is really what I was looking for!Emelia
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 PeruGoodlooking
T
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.

Thurmanthurmann answered 11/11, 2014 at 19:11 Comment(0)
U
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
}
Ulrike answered 16/2, 2016 at 7:51 Comment(0)
P
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.

Protuberate answered 7/11, 2017 at 16:11 Comment(1)
Your approach seems more generic while being more specific on parameters +1Hawn
U
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/

Ulrike answered 4/9, 2015 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.