"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
Impersonation in .NET
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?"
-
Lex Li (Microsoft) 5,582 Reputation points Microsoft Employee
2021-08-18T22:06:20.367+00:00