How to programmatically find out if a user account is a member of a specific group in Windows?

Given the group name and user account, I would like to know if the supplied user belongs to a specific group. A user can be a local user or a domain user, and the group can be a local group or a domain group, and the group can also be nested within other groups. In short, I am looking for a function likebool IsUserMemberOf(User, Group), which will internally call the appropriate Win32 APIs to perform the search. I assume that the process making the above request should have the necessary privileges to request local and AD groups. I assume that starting the process under the account of the administrator of the enterprise should perform the task of requesting any domain controllers in the forest, but may not work for machines that are not part of the domain. Any ideas on which account this query process should run on so that it can query LSA as well as AD?

+3
source share
3 answers

, CheckTokenMembership

UnlockPolicy.c( ), function ShouldUnlockForUser UsagerEstDansGroupe ( ;).

:

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

Source: https://habr.com/ru/post/1711096/


All Articles