1. 程式人生 > >PHP LDAP連線微軟活動目錄進行身份驗證

PHP LDAP連線微軟活動目錄進行身份驗證

如果使用活動目錄(Active Directory)代替在資料庫表中建立賬號, 你可以使用原來Windows網路中的賬號.

LDAP, 輕量級目錄訪問協議(Lightweight Directory Access Protocol), 是用來訪問微軟的活動目錄等目錄伺服器(DS, Directory Server)的協議. PHP預設支援LDAP.

下面是使用LDAP進行使用者身份驗證的PHP程式. 在微軟的活動目錄中, 使用者的唯一標識是"samaccountname", 有些DS是"uid". 方法是:

  1. 用有許可權的賬號的dn(形如 cn=user_name,ou=web,dc=ideawu
    ,dc=com)連線LDAP Server.
  2. 根據登入使用者的名字查詢其dn.
  3. 用該dn連線LDAP Server. 如果連線上就是登入成功.

注意! 微軟的活動目錄伺服器可以使用空賬號連線成功(設定問題? 預設? 特例?)!

$userid = $_POST['userid'];
$user_password = $_POST['password'];

if($userid && $user_password){
// config
// $ldap_server = "ideawu.com";
// $ldap_admin = "user_name";
// $ldap_password = "xxx";
// $base_cn = "ou=web,dc=
ideawu
,dc=com"; $conn = ldap_connect($ldap_server); if(!$conn){ die("<br>Connection LDAP server error"); } $bind = ldap_bind($conn, $ldap_admin, $ldap_password); if(!$bind){ die("<br>Bind LDAP server error"); } $filter = 'samaccountname=' . $userid; $attributes = array('mail'); $result = ldap_search($conn, $base_dn, $filter, $attributes); $info = ldap_get_entries($conn, $result); if(!$result){ die("<br>Search failed"); } if($info["count"] != 0){ $user_dn = $info[0]["dn"]; unset($bind2); $bind2 = @ldap_bind($conn, $user_dn, $user_password); if($bind2){ // Login done. Set session } } ldap_close($conn); }