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.
| Print article | This entry was posted by Jijo Raj on April 16, 2008 at 4:05 pm, and is filed under Uncategorized. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 2 years ago
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.
about 2 years ago
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.
about 2 years ago
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,
about 2 years ago
thanks for the vista info, buddy. Keep sharing your knowledge!
about 1 year ago
Hi maverick_wipro ,
> “IsUserAnAdmin() would fail in Windows Vista if UAC is switched on
about 11 months ago
I get compile errors, can you please post a full example complete with includes and in main() ? Thanks.
about 11 months ago
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.