question

MarkSanchez-5028 avatar image
0 Votes"
MarkSanchez-5028 asked lextm answered

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


dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@MarkSanchez-5028
I suggest you take a look at their source code:
RunImpersonated
Impersonate
Their core code for simulation is the same, they are all calling the SafeImpersonate method.

1 Vote 1 ·

1 Answer

lextm avatar image
1 Vote"
lextm answered

"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://docs.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=net-5.0

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

That answers my question. Thank you

0 Votes 0 ·