C++ LDAP Query to locate memberOf
I am currently trying to perform an LDAP query in c++ to get the memberOf attribute of a given user. I have a function written that successfully gets the attribute if they are only in one group. The problem is that when they are in more than one group it only returns the first one. When I look at the user in Active Directory browser I can see that it says they have 2 entries for memberOf, but when I use my function I only get the first. Is there a way to modify my function to pull back all the entries or am I completely 开发者_Python百科on the wrong path?
bool FindADMembership(CStringArray* pUserArray,IDirectorySearch *pContainerToSearch, CString sAMAccountName){
if(pContainerToSearch==NULL||pUserArray==NULL)
return false;
CString strSearchFilter;
strSearchFilter.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName=%s))", sAMAccountName);
BSTR b = strSearchFilter.AllocSysString();
LPOLESTR pszSearchFilter = b;
ADS_SEARCHPREF_INFO SearchPrefs;
SearchPrefs.dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE;
SearchPrefs.vValue.dwType = ADSTYPE_INTEGER;
SearchPrefs.vValue.Integer = ADS_SCOPE_SUBTREE;
DWORD dwNumPrefs = 1;
LPOLESTR pszColumn = NULL;
ADS_SEARCH_COLUMN col;
HRESULT hr;
IADs *pObj = NULL;
IADs * pIADs = NULL;
ADS_SEARCH_HANDLE hSearch = NULL;
hr = pContainerToSearch->SetSearchPreference( &SearchPrefs, dwNumPrefs);
if (FAILED(hr))
return false;
LPOLESTR pszNonVerboseList[] = {L"memberOf"};
LPOLESTR szName = new OLECHAR[MAX_PATH];
int iCount = 0;
hr = pContainerToSearch->ExecuteSearch(pszSearchFilter, pszNonVerboseList,sizeof(pszNonVerboseList)/sizeof(LPOLESTR),&hSearch);
if ( SUCCEEDED(hr) )
{
hr = pContainerToSearch->GetFirstRow( hSearch);
if (SUCCEEDED(hr))
{
while( hr != S_ADS_NOMORE_ROWS )
{
iCount++;
while( pContainerToSearch->GetNextColumnName( hSearch, &pszColumn ) != S_ADS_NOMORE_COLUMNS )
{
hr = pContainerToSearch->GetColumn( hSearch, pszColumn, &col );
if ( SUCCEEDED(hr) )
{
if (0==wcscmp(L"memberOf", pszColumn))
{
wcscpy(szName,col.pADsValues->CaseIgnoreString);
pUserArray->Add(szName);
}
pContainerToSearch->FreeColumn( &col );
}
FreeADsMem( pszColumn );
}
hr = pContainerToSearch->GetNextRow( hSearch);
}
}
else
return false;
pContainerToSearch->CloseSearchHandle(hSearch);
}
else
return false;
return true; }
Edit:
After working on this here is the code to iterate through the results
if (0==wcscmp(L"memberOf", pszColumn)) {
for(int i = 0; i < col.dwNumValues; i++)
{
wcscpy(szName, col.pADsValues[i].CaseIgnoreString);
pUserArray->Add(szName);
}
}
You need to check the number of values and loop over them to get each in turn - pADSValues
is an array that could contain > 1 string. The count is returned in dwNumValues
.
if (0==wcscmp(L"memberOf", pszColumn))
{
// This code should actually be a loop for i = 0 to dwNumValues - 1
// with each loop checking the next array entry in the list pADsValues
wcscpy(szName,col.pADsValues->CaseIgnoreString);
pUserArray->Add(szName);
}
See docs here.
精彩评论