Code mit anderen Rechten ausführen  
Frank Dzaebel, erstellt am: 18.04.2006, zuletzt geändert:  10.01.2009
Kategorie: Implementation, .NET-Version: 3.5, [Download]

Code wird standardmässig mit den Rechten ausgeführt, die der aktuelle Prozess hat. Das ist im Normalfall dann auch der angemeldete Benutzer. Will man temporär Code mit anderen Rechten ausführen, kann man die API LogonUser, WindowsIdentity.Impersonate nutzen.

Weiterführende Literatur auch:
   Integration von Windows Security mit .NET 2.0 -   Teil1, Teil2, Teil3
   WindowsImpersonationContext-Klasse
   How To: Use Impersonation and Delegation in ASP.NET 2.0


private void button1_Click(object sender, System.EventArgs e)
{
  IntPtr account = IntPtr.Zero;
  WindowsImpersonationContext wiContext = null;

  try
  {
    bool logonErfolgreich = Logon.LogonUser(@"Gast", "", "",
      Logon.LOGON.INTERACTIVE, Logon.PROVIDER.DEFAULT, out account);
    //bool success = Logon.LogonUser(@"Username", "RemotePC", "Passwort",
    // Logon.LOGON.NETWORK, Logon.PROVIDER.DEFAULT, out account);

    if (!logonErfolgreich)
    {
      MessageBox.Show(new Win32Exception().Message);
    }
    else //logonErfolgreich
    {
      wiContext = WindowsIdentity.Impersonate(account);
      MessageBox.Show("neu eingeloggt als " + WindowsIdentity.GetCurrent().Name);

      // ************
      // Aktionen mit den neuen User/account-Rechten
      // ************
    }
  }
  finally
  {
    if (wiContext != null)  wiContext.Undo(); // Identität zurücksetzen
    if (account != IntPtr.Zero) Logon.CloseHandle(account);
  }

  MessageBox.Show("(wieder) eingeloggt als " + WindowsIdentity.GetCurrent().Name);
}