5月 22, 2018

使用 PHP 整合 Windows Active Directory(AD) 進行身份認證

首先安裝 PHP-LDAP 套件:
# apt-get install php-ldap

之後是示範程式碼:
<?php
  $ADserver = "xx.xx.xx.xx";
  $domain   = "example.com.tw";
  $baseDN   = "dc=example,dc=com,dc=tw";
            
  $user     = 'Jack';
  $pass     = 'Password_here';  
  
  /* Format should like Jack@example.com.tw */
  $ldapDN   = $user . '@' . $domain;
  
  $ldapConn = ldap_connect( $ADserver ) or die("Connect fail");
  
  /* IMPORTANT */
  ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);
  ldap_set_option($ldapConn, LDAP_OPT_REFERRALS, 0);

  if ($ldapConn) 
  { 
    $ldapbind = ldap_bind($ldapConn, $ldapDN, $pass);   
    if ($ldapbind) 
    {
      $filter = "(sAMAccountName=$user)";
      $result = @ldap_search($ldapConn, $baseDN, $filter);
      
      if($result == false) 
      {
        /* empty search result */
      }
      else
      {
        $row       = ldap_get_entries( $ldapConn, $result );   
        $loginName = $row[0]['displayname'][0];     // display name
        $loginID   = $row[0]['samaccountname'][0];  // AD account
      }    
    } 
    else 
    {         
      die("User,Pass do not match");
    } 
  }
  ldap_close($ldapConn);  
?>

沒有留言:

張貼留言