【背景】linux
在互聯網大環境下,企業辦公應用近兩年呈現出蓬勃發展的態勢,這些應用必須兼容企業已有的登陸認證系統,LDAP(Lightweight Directory Access Protocol)作爲標準的目錄服務,普遍被企業使用。本文記錄接入到LDAP服務所遇到的問題以及解決辦法,但願對剛接觸LDAP的初學者有所幫助。c++
【環境、語音和開源庫】函數
linuxui
c++spa
OpenLDAPcode
【編譯】blog
從官網ftp://ftp.openldap.org/pub/OpenLDAP/openldap-release/openldap-2.4.44.tgz下載OpenLDAP最新版本ci
一、解壓縮OpenLDAPget
定位到openldap-2.4.44.tgz所在目錄,執行tar zxvf openldap-2.4.44.tgz解壓縮,在當前目錄下生成openldap-2.4.44目錄,ll命令查看包含的子目錄和文件:string
二、vi命令查看INSTALL文件,初步瞭解編譯安裝步驟
三、編譯配置,執行以下命令:
#include 「ldap.h」 using namespace std; LDAP * ld; if ((ld = ldap_init(host.c_str(), LDAP_PORT)) == NULL) { cout << "ldap init failed" << endl; return 1; } int version = LDAP_VERSION3; if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version) != LDAP_SUCCESS) { cout << "set protocol version failed" << endl; return 1; } int max_timeout = 10; if (ldap_set_option(ld, LDAP_OPT_TIMELIMIT, (void *)&max_timeout) != LDAP_SUCCESS) { cout << "set time limit failed" << endl; return 1; } // must do set if (ldap_set_option(ld,LDAP_OPT_REFERRALS,LDAP_OPT_OFF) != LDAP_SUCCESS) { cout << "set referrals off failed" << endl; return 1; } // dn,pw管理員帳戶和密碼 int ret = LDAP_SUCCESS; if ((ret = ldap_simple_bind_s(ld, dn_admin, pw_admin)) != LDAP_SUCCESS) { cout << "ldap_simple_bind_s failed" << endl; cout << "errcode : " << ret << endl; cout << "errmsg : " << ldap_err2string(ret) << endl; return 1; } LDAPMessage *result, *msg; char * attrs[1]; attrs[0] = "distinguishedName"; char * filter = "(&(objectclass=user)(sAMAccountName=loginName))"; char * base = "DC=MyCompany,DC=com"; if ((ret = ldap_search_s(ld, base, LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result)) != LDAP_SUCCESS) { cout << "ldap_search_s failed" << endl; cout << "errcode :" << ret << endl; cout << "errmsg : " << ldap_err2string(ret) << endl; return 1; } char **vals; if ((msg = ldap_first_entry(ld, result)) != NULL) { if ((vals = ldap_get_values(ld, msg, "distinguishedName")) != NULL) { char * dn = ldap_get_dn(ld, msg); ret = ldap_simple_bind_s(ld, dn, pw) if (ret == LDAP_SUCCESS) { cout << "auth succ"; } else { cout << "auth failed"; } }