如何获取用于Active Directory API的IADsUser对象?

时间:2018-11-19 20:52:35

标签: c++ winapi active-directory

如何设置传入参数pUser传递给此函数CheckUserGroups(IADsUser * pUser)?我在另一篇文章中看到了函数,但是他们没有详细解释:Need to retrieve all groups a user belongs to... in C++

请告知。

HRESULT CheckUserGroups(IADsUser *pUser)
{
  IADsMembers *pGroups;
  HRESULT hr = S_OK;

  hr = pUser->Groups(&pGroups);
  pUser->Release();
  if (FAILED(hr)) return hr;

  IUnknown *pUnk;
  hr = pGroups->get__NewEnum(&pUnk);
  if (FAILED(hr)) return hr;
  pGroups->Release();

  IEnumVARIANT *pEnum;
  hr = pUnk->QueryInterface(IID_IEnumVARIANT,(void**)&pEnum);
  if (FAILED(hr)) return hr;

  pUnk->Release();

  // Enumerate.
  BSTR bstr;
  VARIANT var;
  IADs *pADs;
  ULONG lFetch;
  IDispatch *pDisp;

  VariantInit(&var);
  hr = pEnum->Next(1, &var, &lFetch);
  while(hr == S_OK)
  {
    if (lFetch == 1)
    {
      pDisp = V_DISPATCH(&var);
      pDisp->QueryInterface(IID_IADs, (void**)&pADs);
      pADs->get_Name(&bstr);
      printf("Group belonged: %S\n",bstr);
      SysFreeString(bstr);
      pADs->Release();
    }
    VariantClear(&var);
    pDisp=NULL;
    hr = pEnum->Next(1, &var, &lFetch);
  };
  hr = pEnum->Release();
  return S_OK;
}

1 个答案:

答案 0 :(得分:2)

以下是创建和设置IADsUser *pUser(将“管理员”更改为您的用户名)的示例:

    HRESULT hr = S_OK;
    IADsUser *pUser;
    _bstr_t bstr;
    DWORD ll_len = 255;
    char lbBuffer[255];
    ::GetComputerName(lbBuffer, &ll_len);

    bstr = "WinNT://" + _bstr_t(lbBuffer) + "/" + _bstr_t("Administrator") + ",user";

    hr = CoInitialize(NULL);
    hr = ADsGetObject(bstr, IID_IADsUser, (void **)&pUser);

    if (SUCCEEDED(hr))
    {
        hr = CheckUserGroups(pUser);
        /*
        hr = pUser->SetPassword(_bstr_t("123456"));

        if (SUCCEEDED(hr))
        {
            CoUninitialize();
            return TRUE;
        }
        */
    }
    CoUninitialize();

对于LDAP,您可以从this document中的示例获取帮助,更改ADsGetObject的第一个参数。