简体   繁体   中英

Check if process user is an administrator c++

I want to get the process's user name and check if it is a local administrator . Or check directly if the current procees user is a local administrator

Get the current username with , then call NetUserGetInfo() with the server name (NULL for local) and username you just got. 获取当前用户名,然后使用服务器名称(本地为NULL)和刚获得的用户名调用NetUserGetInfo()Pass it a USER_INFO_1 structure, and then access in the structure. If the value is USER_PRIV_ADMIN , then you'll know that the username is an admin.

Tested on Windows XP SP3, Windows 7 32 bit and 64 bit with admin user and non-admin user. Code ported from equivalent C# and uses ATL windows security wrapper classes.

#include <atlbase.h>
#include <atlsecurity.h>

// The function returns true if the user who is running the
// application is a member of the Administrators group,
// which does not necessarily mean the process has admin privileges.
bool IsAdministrator(HRESULT &rHr)
{
    bool bIsAdmin = false;

    try
    {
        // Open the access token of the current process.
        ATL::CAccessToken aToken;
        if (!aToken.GetProcessToken(TOKEN_QUERY))
        {
            throw MAKE_SCODE(SEVERITY_ERROR, FACILITY_WIN32,
                ::GetLastError());
        }


        // Query for the access token's group information.
        ATL::CTokenGroups groups;
        if (!aToken.GetGroups(&groups))
        {
            throw MAKE_SCODE(SEVERITY_ERROR, FACILITY_WIN32,
                ::GetLastError());
        }

        // Iterate through the access token's groups
        // looking for a match against the builtin admins group.
        ATL::CSid::CSidArray groupSids;
        ATL::CAtlArray<DWORD> groupAttribs;
        groups.GetSidsAndAttributes(&groupSids, &groupAttribs);
        for (UINT i = 0; !bIsAdmin && i < groupSids.GetCount(); ++i)
        {
            bIsAdmin = groupSids.GetAt(i) == ATL::Sids::Admins();
        }
        rHr = S_OK;
    }
    catch (HRESULT hr)
    {
        rHr = hr;
    }

    return bIsAdmin;
}

Presuming you're on a Window OS there's a shell function: IsUserAnAdmin

See MSDN article

This article does suggest rolling your own function though, use CheckTokenMembership . There is even a code example to help you along.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM