How to programmatically figure out if a user account is a member of a particular group in Windows?

纵然是瞬间 提交于 2019-11-30 15:49:42

You need to read up on GetTokenInformation (TOKEN_USER), AllocateAndInitializeSid and CheckTokenMemberShip.

UserPrincipal.IsMemberOf(GroupPrincipal) "returns a Boolean value that specifies whether the principal is a member of the specified group".

Magnus is right, you must use CheckTokenMembership

You can find a sample in UnlockPolicy.c (download the full source here), function ShouldUnlockForUser and UsagerEstDansGroupe (excuse my French;).

Here is the guts of it :

HRESULT IsUserInGroup(HANDLE user, const wchar_t* groupe)
{
    HRESULT result = E_FAIL;
    SID_NAME_USE snu;
    WCHAR szDomain[256];
    DWORD dwSidSize = 0;
    DWORD dwSize = sizeof szDomain / sizeof * szDomain;

    if ((LookupAccountNameW(NULL, groupe, 0, &dwSidSize, szDomain, &dwSize, &snu) == 0)
            && (ERROR_INSUFFICIENT_BUFFER == GetLastError()))
    {
        SID* pSid = (SID*)malloc(dwSidSize);

        if (LookupAccountNameW(NULL, groupe, pSid, &dwSidSize, szDomain, &dwSize, &snu))
        {
            BOOL b;

            if (CheckTokenMembership(user, pSid, &b))
            {
                if (b == TRUE)
                {
                    result = S_OK;
                }
            }
            else
            {
                result = S_FALSE;
            }
        }

        //Si tout vas bien (la presque totalitée des cas), on delete notre pointeur
        //avec le bon operateur.
        free(pSid);
    }

    return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!