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 could be a local group or a domain group and the group could also be nested inside other groups. In short I am looking for a function like bool IsUserMemberOf(User, Group)
that will internally call the appropriate Win32 APIs to do the search. I guess the process making the above query should have the necessary privileges to query local and AD groups. I guess runing the process under enterprise admin account should do the job of querying any DCs in the forest but may not work for machines that are not part of a domain. Any ideas on what account this querying process should run so that it can query the LSA as well as the AD?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You need to read up on GetTokenInformation (TOKEN_USER), AllocateAndInitializeSid and CheckTokenMemberShip.
回答2:
UserPrincipal.IsMemberOf(GroupPrincipal) "returns a Boolean value that specifies whether the principal is a member of the specified group".
回答3:
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;
}