如何检查用户是否在win32中具有本地管理员权限

时间:2009-02-24 10:16:05

标签: c++ winapi

如何检查用户是否具有来自c ++的win32的本地管理员权限

2 个答案:

答案 0 :(得分:9)

刚刚在shlobj.h找到了IsUserAnAdmin(),这对我有用。

答案 1 :(得分:3)

你可能需要更多来处理高程等... ...

我这样做....

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
}

我不记得我从哪里获取信息来编写那段代码......