Scope Windows impersonation to one operation

WindowsIdentity.RunImpersonated runs a delegate under a supplied Windows access token and restores the surrounding identity afterward. It gives the impersonated operation an explicit lifetime.

This is Windows-specific. Acquiring a token for another user is a separate, authorized authentication step. Never embed that user's password in source or a plain-text web configuration.

Observe the scoped API

Create a .NET console project on Windows and use this Program.cs:

C#
using System.Security.Principal;

if (!OperatingSystem.IsWindows()) return;
using var identity = WindowsIdentity.GetCurrent();
var name = WindowsIdentity.RunImpersonated(identity.AccessToken, () => {
	using var current = WindowsIdentity.GetCurrent();
	return current.Name;
});
Console.WriteLine(name);

Run dotnet run. Expect the current Windows account name. This deliberately uses the current identity's token to demonstrate the lifetime without acquiring credentials or changing privileges. An application with an already authorized target token can supply that token to the same API.

Keep ownership and delegation explicit

Retain the token's owning identity or safe handle for the duration of the call. In a Windows-authenticated server request, the authenticated identity and the process identity are not necessarily the same. Use impersonation only around the resource operation that requires it, after authorization.

For asynchronous work, use the supported asynchronous impersonation API and await its completion. Avoid fire-and-forget work that outlives the intended scope. Impersonation does not automatically solve the network double-hop problem. Accessing another server under the caller's identity requires the appropriate delegation configuration.

Do not grant broad operating-system privileges as a generic fix for access errors. Verify the token, resource permissions, logon/delegation requirements and hosting identity for the actual operation.

Official references

WindowsIdentity.RunImpersonated Method (System.Security.Principal)
Runs the specified action as the impersonated Windows identity. Instead of using an impersonated method call and running your function in WindowsImpersonationContext, you can use RunImpersonated(SafeAccessTokenHandle, Action) and provide your function directly as a parameter.
https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=net-10.0
WindowsIdentity.RunImpersonated

Author: Herman Schoenfeld