Alex Rivera | Logout

How do you do Impersonation in .NET?

Asked 2008-09-24T03:55:09.147
161

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.

Edit
Report

1 Answer

342

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

answered 2011-08-30T21:39:17.017

Your Answer