How do I check if a user has local admin privileges in win32 from c++
Just found IsUserAnAdmin() in shlobj.h which does the job for me.
You might need more than that to deal with elevation and such like...
I do it like this....
bool CProcessToken::IsUserAnAdmin() const
{
#if _WIN32_WINNT >= 0x0600
bool isAdmin = false;
DWORD bytesUsed = 0;
TOKEN_ELEVATION_TYPE tokenElevationType;
if (!::GetTokenInformation(m_hToken, TokenElevationType, &tokenElevationType, sizeof(tokenElevationType), &bytesUsed))
{
const DWORD lastError = ::GetLastError();
throw CWin32Exception(_T("CProcessToken::IsUserAnAdmin() - GetTokenInformation - TokenElevationType"), lastError);
}
if (tokenElevationType == TokenElevationTypeLimited)
{
CSmartHandle hUnfilteredToken;
if (!::GetTokenInformation(m_hToken, TokenLinkedToken, reinterpret_cast<void *>(hUnfilteredToken.GetHandle()), sizeof(HANDLE), &bytesUsed))
{
const DWORD lastError = ::GetLastError();
throw CWin32Exception(_T("CProcessToken::IsUserAnAdmin() - GetTokenInformation - TokenLinkedToken"), lastError);
}
BYTE adminSID[SECURITY_MAX_SID_SIZE];
DWORD sidSize = sizeof(adminSID);
if (!::CreateWellKnownSid(WinBuiltinAdministratorsSid, 0, &adminSID, &sidSize))
{
const DWORD lastError = ::GetLastError();
throw CWin32Exception(_T("CProcessToken::IsUserAnAdmin() - CreateWellKnownSid"), lastError);
}
BOOL isMember = FALSE;
if (::CheckTokenMembership(hUnfilteredToken, &adminSID, &isMember))
{
const DWORD lastError = ::GetLastError();
throw CWin32Exception(_T("CProcessToken::IsUserAnAdmin() - CheckTokenMembership"), lastError);
}
isAdmin = (isMember != FALSE);
}
else
{
isAdmin = ToBool(::IsUserAnAdmin());
}
return isAdmin;
#else
return ToBool(::IsUserAnAdmin());
#endif
}
I can't remember where I got the information from to write that bit of code though...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With