views:

1774

answers:

2

I have an application that needs to detect whether or not it is running with elevated privileges or not. I currently have code set up like this:

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

This works to detect if a user is an administrator or not, but doesn't work if running as an administrator without elevation. (For example in vshost.exe). How can I determine whether or not the applicaiton is elevated or not?

+4  A: 

The codeplex project UAChelper has code that checks on elevation in UserAccountControl.cpp UserAccountControl::IsUserAdmin that checks if UAC is enabled and then checks is process is elevated.

bool UserAccountControl::IsCurrentProcessElevated::get()
{
 return GetProcessTokenElevationType() == TokenElevationTypeFull; //elevated
}

from the function:

int UserAccountControl::GetProcessTokenElevationType()
{
 HANDLE hToken;
try
{
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
   throw gcnew Win32Exception(GetLastError());

    TOKEN_ELEVATION_TYPE elevationType;
  DWORD dwSize;
    if (!GetTokenInformation(hToken, TokenElevationType, &elevationType, sizeof(elevationType), &dwSize))
        throw gcnew Win32Exception(GetLastError());

  return elevationType;
}
finally
{
    CloseHandle(hToken);
}
}
Preet Sangha
+3  A: 

Using TokenElevationType would work, but if you PInvoke CheckTokenMembership() against the admin group SID, your code would also work when UAC is off and on 2000/XP/2003 and will also handle deny SID's.

There is also a IsUserAnAdmin() function that does the CheckTokenMembership check for you, but MSDN says it might not be there forever

Anders