本文主要是介绍LDAP 认证(Linux),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
作者: 一去、二三里
个人微信号: iwaleon
微信公众号: 高效程序员
之前分享过 LDAP 认证(Windows) 的相关内容,为了跨平台,针对 Linux 也进行相关的实现。
基本使用
使用时依赖库 libldap.so(/usr/lib64),头文件所在目录 /usr/include。
#include <stdio.h>
extern "C" {#define LDAP_DEPRECATED 1#include <ldap.h>#include <lber.h>
}// LDAP 服务器的设置
#define HOST "172.18.***.***"
#define PORT LDAP_PORT
#define WHO "uid=username,ou=People,dc=cloud,dc=com"
#define PASSWD "password"
#define FIND_DN "ou=People,dc=cloud,dc=com"bool auth()
{LDAP *ld;LDAPMessage *result, *e;BerElement *ber;char *a;char **vals;int i, rc;int i_version = LDAP_VERSION3;// 获取 LDAP 连接的句柄ld = ldap_init(HOST, PORT);if (ld == NULL) {perror("ldap_init");return false;}printf("ldap_init success\n");// 设置协议版本ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &i_version);ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON);// 绑定到 LDAP 服务器rc = ldap_simple_bind_s(ld, WHO, PASSWD);if (rc != LDAP_SUCCESS) {fprintf(stderr, "ldap_simple_bind_s: rc: %d, %s\n", rc, ldap_err2string(rc));return false;}printf("ldap_simple_bind_s success\n");// 搜索条目rc = ldap_search_ext_s(ld, FIND_DN, LDAP_SCOPE_BASE, "(objectclass=*)",NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &result);if (rc != LDAP_SUCCESS) {fprintf(stderr, "ldap_search_ext_s: rc: %d, %s\n", rc, ldap_err2string(rc));return false;}printf("ldap_search_ext_s success\n");// 由于正在做基本搜索,所以应该只有一个匹配的条目e = ldap_first_entry(ld, result);if (e != NULL) {printf("\nFound %s:\n\n", FIND_DN);// 迭代条目中的每个属性for (a = ldap_first_attribute(ld, e, &ber); a != NULL; a = ldap_next_attribute(ld, e, ber)) {// 对于每个属性,打印属性名称和值if ((vals = ldap_get_values( ld, e, a)) != NULL) {for (i = 0; vals[i] != NULL; i++) {printf("%s: %s\n", a, vals[i]);}ldap_value_free(vals);}ldap_memfree(a);}if (ber != NULL)ber_free(ber, 0);}ldap_msgfree(result);ldap_unbind(ld);return true;
}
更多参考
- Lightweight Directory Access Protocol
- LDAP Functions
这篇关于LDAP 认证(Linux)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!