title: How to check if user is an administrator on that machine
body: <p>I need to check if a user is an administrator on the machine where the application is running. Basically, the user will provide the username, password and domain, possibly from another machine. These are transmitted over WCF and at this stage I need to verify whether the provided username, password and domain have admin rights on that machine. This means that there is no need for WMI since everything is happening locally (the user simply sent the username, password, domain as strings over WCF)</p>
  
  <p>Users can be on a domain and hence linked to Active Directory but can can also be a local user, which means that I cannot reply to look it up from Active Directory.</p>
  
  <p>I managed to impersonate the user and can verify that this user is an administrator in the local group. I tested this using the following command:</p>
  
  <pre><code>net localgroup administrators
  </code></pre>
  
  <p>I am now creating a WindowsPrincipal with the current impersonated user. However, I am getting false when checking if this user is an admin. Here is the important code:</p>
  
  <pre><code>// obtains user token
  [DllImport("advapi32.dll", SetLastError=true)]
  public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, 
      int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
  
  // closes open handes returned by LogonUser
  [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
  public extern static bool CloseHandle(IntPtr handle);
  
  // creates duplicate token handle
  [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
  public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, 
      int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
  
  bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,  LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
  
  bool bRetVal = DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);
  
  WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
  WindowsImpersonationContext impersonatedUser = newId.Impersonate();
  WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
  
  if (wp.IsInRole(WindowsBuiltInRole.Administrator))
  {
      //is admin
  }
  else
  {
      //is not an admin (I am still getting this when user is an admin)
  }
  </code></pre>
  
  <p>bImpersonated returns true (so Impersonation worked)
  bRetVal also returns true (so token is valid)</p>
  
  <p>The Impersonation code is from <a href="http://www.codeproject.com/Articles/4051/Windows-Impersonation-using-C" rel="nofollow">here</a> (except for the Admin check)</p>
  
  <p>Any help would be greatly appreciated.</p>