環境
- OS: Windows 10 Pro
- WSL2
- ディストリビューション: Ubuntu20.04
 
- Ubuntu には node.js や npm などはインストール済み
やること
WLS 内の Ubuntu から、物理的に別サーバーで立てている Windows の ActiveDirectory に対して LDAP 認証をしてみます。
具体的に、Ubuntu から node.js を使用して LDAP 認証を試してみます。
手順
1. とりあえず LDAP 認証をしてみる
ググり方が悪いのか、なかなか参考になる情報が見つからなかったのですが、↓が見つかり非常に参考になりした。
https://learntutorials.net/ja/node-js/topic/10612/node-jsでのwindows認証
# ベースとなる node のプロジェクトを作る
$ mkdir ldap_test
$ cd ldap_test
$ npm init
# AD へアクセスするためのモジュールをインストール
$ npm install --save activedirectory
# サンプルソースを書く
$ touch index.jsここで、上記サイト様の抜粋になりますが、 index.js には以下のようにサンプルソースを書きます。
// Initialize
var ActiveDirectory = require('activedirectory');
var config = {
  url: 'ldap://hoge.com', // ADのホスト名
  baseDN: 'dc=hoge,dc=com'    // ホスト名を「.」で分割したもの。多分なくても大丈夫
};
var ad = new ActiveDirectory(config);
var username = 'tonnura@hoge.com';    // ユーザー名
var password = 'xxxxxxx';     // パスワード
// Authenticate
ad.authenticate(username, password, function (err, auth) {
  if (err) {
    console.log('ERROR: ' + JSON.stringify(err));
    return;
  }
  if (auth) {
    console.log('Authenticated!');
  }
  else {
    console.log('Authentication failed!');
  }
});実行してみると、以下のようになり成功しました。
$ node index.js
Authenticated!2.LDAP サーバーから個人情報を取得する
上記の続きとなりますが、今度は認証だけでなく、名前や所属情報などの個人情報も取得します。
↓も参考にしました。
https://www.npmjs.com/package/activedirectory
// Initialize
var ActiveDirectory = require('activedirectory');
var username = 'tonnura@hoge.com';    // ユーザー名
var password = 'xxxxxxx';     // パスワード
var config = {
  url: 'ldap://hoge.com', // ADのホスト名
  baseDN: 'dc=hoge,dc=com',   // ホスト名を「.」で分割したもの。多分なくても大丈夫
  username: username,   // ★ config にあらかじめユーザー名を追加
  password: password,   // ★ config にあらかじめパスワードを追加
};
// Authenticate
var ad = new ActiveDirectory(config);   // 引数にユーザー名とパスワードが負荷されているので、ここで認証処理も実施される
console.log('Authenticated!');
// Get
ad.getGroupMembershipForUser(username, function (err, groups) { // またユーザー名を引数に渡すのは冗長なのですが、こういう仕様っぽいです・・・
  if (err) {
    console.log('ERROR: ' + JSON.stringify(err));
    return;
  }
  if (!groups) console.log('User: ' + sAMAccountName + ' not found.');
  else console.log(JSON.stringify(groups));
});実行してみると、以下のようになり成功しました。
$ node index.js
Authenticated!
[{"dn":"CN=xxxx,OU=xxxx,DC=xxxx,DC=xxxx","cn":"xxxx"},{"dn":"CN=xxxx,OU=xxxx,DC=xxxx,DC=xxxx","cn":"xxxx"}]ここで重要なのが、new ActiveDirectory(config) 実行時に既にユーザー名とパスワードを設定しておくことです。
こうしないと以下のようなエラーが出ました。
ERROR: {"lde_message":"000004DC: LdapErr: DSID-0C090A59, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v4563\u0000","lde_dn":null} 
  
  
  
  
コメント