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

后端 未结 3 1468
夕颜
夕颜 2020-12-17 05:39

Given a group name and a user account, I would like to know if the supplied user belongs to a particular group. The user can be a local user or a domain user and the group c

相关标签:
3条回答
  • 2020-12-17 05:56

    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;
    }
    
    0 讨论(0)
  • 2020-12-17 05:58

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

    0 讨论(0)
  • 2020-12-17 06:09

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

    0 讨论(0)
提交回复
热议问题