For a small utility app I'm writing at work, I have the following code to determine if the current user account is a local or domain administrator:
WCHAR wszUser[UNLEN];
GetEnvironmentVariableW(L"username", wszUser, UNLEN);
#ifndef _DEBUG
if (StrCmpIW(wszUser, L"Administrator") != 0)
{
MessageBoxW(0, L"This program can only be run as Administrator.", L"Error", MB_OK | MB_ICONSTOP);
return 0;
}
#endif
This works in our case right now because:
However, I realize that this is a bad solution because in the future we might add other domain administrator accounts. Is there a way to determine using the Windows API whether the user account that the process is running from belongs to either the Domain Admins group, or BUILTIN\Administrators
, or not?
This is not a security concern since the app won't actually be able to do anything useful unless it's running as an Administrator, this is just for robustness.
The correct solution in this case is to set the /MANIFESTUAC:level=requireAdministrator
linker option, or if you already have a manifest, add a requestedExecutionLevel
entry as described here.
That way, Windows will refuse to run the program without elevated privileges, and you don't need to do anything in your code. This will also make it easier on the user, because they don't have to explicitly run your code elevated in order for it to work; Windows will prompt them as necessary.
However, if you really want to do it programmatically, see the documentation for the CheckTokenMembership function, which even has example code that does exactly what you are asking for. :-)