Search code examples
c#.net.net-4.5impersonation

Execute Code in an Unelevated Context


My application is running as an administrator (elevated), but I need to run certain blocks of code in the current user's context (unelevated).

  1. How can I run a given block of code in an unelevated context?

    Is there a way to do this with impersonation, that doesn't require me to know the user's domain, name, and password?

    Is there another API for this, or a way to do it simply with attributes?

  2. Likewise, is there a way to detect that I'm currently running in an elevated context, so that I know I need to de-elevate in the first place?

I'm using C# 6.0, .NET 4.x (where x >= 5), and Visual Studio 2015.


Solution

    1. You can achieve this by encapsulating the code that needs to run un-elevated in a separate assembly (.exe file) and start it as a new process. Take a look at Start non-elevated process from elevated process.
    2. To check if you're in elevated context:

      static bool IsAdministrator()
      {
          WindowsIdentity identity = WindowsIdentity.GetCurrent();
          WindowsPrincipal principal = new WindowsPrincipal(identity);
          return principal.IsInRole (WindowsBuiltInRole.Administrator);
      }
      

      (Taken from: Detect if running as Administrator with or without elevated privileges?)