Freigeben über


Impersonation

Impersonation lets you execute code using another user identity. In the WindowsIdentity class, there's a method called Impersonate, it allows you to impersonate the user specified by the WindowsIdentity instance. Just remember to call Undo to get back to the original identity. Here's an example from MSND:

private static void ImpersonateIdentity(IntPtr logonToken)
{
    // Retrieve the Windows identity using the specified token.
    WindowsIdentity windowsIdentity = new WindowsIdentity(logonToken);

    // Create a WindowsImpersonationContext object by impersonating the
    // Windows identity.
    WindowsImpersonationContext impersonationContext = windowsIdentity.Impersonate();

    Console.WriteLine("Name of the identity after impersonation: " + WindowsIdentity.GetCurrent().Name + ".");
    Console.WriteLine(windowsIdentity.ImpersonationLevel);

// Stop impersonating the user.
    impersonationContext.Undo();

    // Check the identity name.
    Console.Write("Name of the identity after performing an Undo on the");
    Console.WriteLine(" impersonation: " + WindowsIdentity.GetCurrent().Name);
}

For more info, please read: WindowsIdentity.Impersonate Method