How to auth windows AD users by node.js?

2019-04-17 05:45发布

问题:

I need to auth windows AD users recently. The scenario is below

  • Web pages runs at Server A ( Vue + vue-router )
  • Api interface runs at Server B ( node + express )
  • User input AD username & pwd on Web pages (Server A)
  • pass the username & pwd to the api interface on Server B to auth
  • Server B auth username & pwd via LDAP(windwos AD)
  • api on Server B returns the feedback to Web pages (Server A)

So, is there any solution could be implemented on Server B to auth username & pwd via LDAP?

Great thx!

回答1:

I have used nodesspi https://github.com/abbr/nodesspi.

But it is only for windows env. And it seems that u can get the results via browser only to visit server B directly. Not passing param to call api on server B.

Anyway, it is a good scenario to study for me.



回答2:

I found the solution. refer to: Node JS LDAP Auth User

var ldap = require('ldapjs');
var client = ldap.createClient({
  url: 'ldap://ldapserver:port/',
  timeout: 5000,
  connectTimeout: 10000
});
var opts = {
  filter: '(&(cn=*))',
  scope: 'sub',
  // This attribute list is what broke your solution
  attributes:['SamAccountName','dn']
};
console.log('--- going to try to connect user ---');
try {
   client.bind(username, password, function (error) { //first need to bind
        if(error){
            console.log(error.message);
              client.unbind(function(error) {if(error){console.log  (error.message);} else{console.log('client disconnected');}});
    } else {
        console.log('connected');
        client.search('ou=users, ou=compton, dc=batman, dc=com', opts, function(error, search) {
            console.log('Searching.....');

            search.on('searchEntry', function(entry) {
                if(entry.object){
                    console.log('entry: %j ' + JSON.stringify(entry.object));
                }
                client.unbind(function(error) {if(error){console.log(error.message);} else{console.log('client disconnected');}});
            });

            search.on('error', function(error) {
                console.error('error: ' + error.message);
                client.unbind(function(error) {if(error){console.log(error.message);} else{console.log('client disconnected');}});
            });

    }
});
} catch(error){
   console.log(error);
   client.unbind(function(error) {if(error){console.log(error.message);}       else{console.log('client disconnected');}});
}

remember if you get 'error~~~: Size Limit Exceeded' error, use paged and sizeLimit param.

var opts = {
 filter: '(objectclass=commonobject)',
 scope: 'sub',
 paged: true,
 sizeLimit: 200
};