How do I check if a user has local admin privileges in win32 from c++
+5
A:
Just found IsUserAnAdmin() in shlobj.h which does the job for me.
Tony Edgecombe
2009-02-24 11:10:27
+3
A:
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...
Len Holgate
2009-02-24 11:14:49
Fortunately I can ignore elevation at the moment as I request elevation in the manifest, this is just for pre Vista installs.
Tony Edgecombe
2009-02-24 12:21:24