Gold mine of Visual C++ tricks!
How to check whether current user have administrator privilege?
![]()
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.
If you use the IsUserAnAdmin() function, you can achive the same result as above. Basically the IsUserAnAdmin() internally use SHTestTokenMembership() function and that function internally perform the same operation you mentioned in the above tip.
That function is intentionally ignored. See the extract from MSDN “This function is a wrapper for CheckTokenMembership. It is recommended to call that function directly to determine Administrator group status rather than calling IsUserAnAdmin.”
But i forgot to add that info as a note.
I think it will be useful. Thanks for pointing it out.
IsUserAnAdmin() would fail in Windows Vista if UAC is switched on… u can find out if admin priv in by a write to \HKLM , copying to \system32,
thanks for the vista info, buddy. Keep sharing your knowledge!
Hi maverick_wipro ,
> “IsUserAnAdmin() would fail in Windows Vista if UAC is switched on
I get compile errors, can you please post a full example complete with includes and in main() ? Thanks.
Hi Axe,
Could you post the errors you got? So that i can troubleshoot.
Are you trying to build the code in a console project?
Best Regards,
Jijo.
[...] http://weseetips.com/2008/04/16/how-to-check-whether-current-user-have-administrator-privilege/ [...]