Impersonation in .NET

Mark Sanchez 101 Reputation points
2021-08-17T21:41:11.487+00:00

In a few of our C# custom desktop apps, we have long used a class that allows us (while running in the context of a user) to briefly impersonate a privileged account, carry out some action (ex: copy a file from a place the user does not have access to), then returns the context back to the user. I am performing a security and best practices review and have noted that while our method to perform the impersonation remains valid, there is an alternative method.

Within the context of the System.Security.Principal, there is both a "Impersonate" and "RunImpersonated" method. Can anyone expound on whether one method is better than the other? I got the idea from an old StackOverflow post (User Matt Johnson-Pint who mentions .NET FW 4.6+ should use RunImpersonated). My question is "why?"

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,314 questions
{count} votes

Accepted answer
  1. Lex Li (Microsoft) 4,742 Reputation points Microsoft Employee
    2021-08-18T22:06:20.367+00:00

    "This method may be used reliably with the async/await pattern, unlike Impersonate. In an async method, the generic overload of this method may be used with an async delegate argument so that the resulting task may be awaited." If you read carefully https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=net-5.0

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful