NodeJS 链接LDAP
LDAP是一个轻量级的目录访问协议。关于LDAP更多解读,参考:
http://www.openldap.org/
https://baike.baidu.com/item/LDAP/2875565?fr=aladdin
通过以上,了解基本概念、:DN、basic_dn…..
ldap认证过程
局域网内用户若需要统LDAP进行认证,则需要对应的应用服务接入LDAP。(假设LDAP服务已建立)
使用 NodeJS 来进行访问LDAP服务器,进行用户基本信息验证和校验。
其中,NodeJS有一个第三分包叫 ldapjs 封装了与ldap进行通信的方法。
| 12
 3
 4
 5
 
 | 官方网站:
 http://ldapjs.org/
 
 https://github.com/mcavage/node-ldapjs
 
 | 
通过LDAP验证用户合法性过程:
- 前端获取用户输入的用户名+密码 
- 将用户名和密码传给后端上层接口 接口做基本校验(如:验证码是否ok等) 
- 上层接口使用具有管理权限的口令进行 - bind操作 (会通过- LDAP扩展=> ldapjs )
 
- bind操作成功后, 并根据用户名获取该用户的- DN(- search操作, Search不到该用户返回错误,反之返回该用户的所有信息)
 
- 根据第三步获取dn, 加上用户的密码再次进行 - bind, LDAP服务器会根据密码是否ok返回结果
 
- 接口处理完毕返回对应信息给前端 
进行封装
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 
 | const ldap = require('ldapjs');
 
 const ldapConfig = require('../config/config');
 
 var ldapAuth = {
 
 
 
 
 
 
 loginAuth: function(username, userPassword) {
 
 let client = ldap.createClient({
 url: ldapConfig.url
 });
 let options = {
 filter: '(sAMAccountName=' + username + ')',
 scope: 'sub',
 timeLimit: 500
 };
 
 return new Promise(function(resolve, reject) {
 client.bind(ldapConfig.adminDn, ldapConfig.adminPwd, function(err, matched) {
 client.search(ldapConfig.bashDn, options, function(err, res2) {
 res2.on('searchEntry', function(entry) {
 
 
 let user = entry.object;
 
 
 
 userDN = user.dn;
 
 client.bind(userDN, userPassword, function(err, res) {
 if (err) {
 
 reject(err);
 } else {
 
 resolve(user);
 }
 });
 
 });
 
 res2.on('searchReference', function(referral) {
 
 });
 
 
 res2.on('error', function(err) {
 console.error('error: ' + err.message);
 
 client.unbind();
 });
 
 
 res2.on('end', function(result) {
 
 
 client.unbind();
 });
 
 });
 });
 });
 }
 };
 
 module.exports = ldapAuth;
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | 'use strict';
 
 var ldapConfig = {
 url: "ldap://xx..xxx:389/",
 adminDn: "admin name",
 adminPwd: "admin password",
 bashDn: "basic DN"
 };
 
 module.exports = ldapConfig;
 
 | 
注意到,ldap.js组件导出的是一个 ldapAuth 对象, 该对象封装了 loginAuth 方法 且该方法返回的是一个 Promise对象。
那么如何使用呢?
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | var ldapAuth = require('../components/ldap');
 var verify = async function() {
 try {
 let res = await ldapAuth.loginAuth("testName", "testPwd");
 
 console.log(res);
 } catch (err) {
 console.log("用户名或密码不正确!");
 }
 };
 
 verify();
 
 
 | 
测试及结构如下图:
POSTMAN 测试:
参考
http://www.jb51.net/article/72954.htm
async/await
https://cnodejs.org/topic/5640b80d3a6aa72c5e0030b6
http://www.ruanyifeng.com/blog/2015/05/async.html
http://www.runoob.com/nodejs/nodejs-express-framework.html