How to check whether current user have administrator privilege?

16 04 2008


Some applications need special administrator privilege to function. Several application won’t even start if you don’t have administrator privilege. They just pops an error and exit. So, how to check whether the current user have admin privilege or not?


You can use the function – CheckTokenMembership(). See the code snippet below. Its modified and taken from MSDN.

SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
// Initialize SID.
if( !AllocateAndInitializeSid( &NtAuthority,
                               2,
                               SECURITY_BUILTIN_DOMAIN_RID,
                               DOMAIN_ALIAS_RID_ADMINS,
                               0, 0, 0, 0, 0, 0,
                               &AdministratorsGroup))
{
    // Initializing SID Failed.
    return false;
}
// Check whether the token is present in admin group.
BOOL IsInAdminGroup = FALSE;
if( !CheckTokenMembership( NULL,
                           AdministratorsGroup,
                           &IsInAdminGroup ))
{
    // Error occurred.
    IsInAdminGroup = FALSE;
}
// Free SID and return.
FreeSid(AdministratorsGroup);
return IsInAdminGroup;


Targeted Audience – Intermediate.

Advertisements