顯示具有 AD 標籤的文章。 顯示所有文章
顯示具有 AD 標籤的文章。 顯示所有文章

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);  
?>

12月 12, 2017

使用 C# 透過 Active Directory 驗證使用者

using System.DirectoryServices; 

static void Main(string[] args)
{
    string Username = "0MXXX";
    string Password = "AbXXX";
    DirectoryEntry entry = new DirectoryEntry("ADserver.domain.com.tw");
    entry.Path = "LDAP://DC=domain,DC=com,DC=tw";
    DirectorySearcher search = new DirectorySearcher(entry);

    /* Must using 'SAMAccountName' here */
    search.Filter = "(&(SAMAccountName=" + Username + "))";

    SearchResult result = search.FindOne();    
    string DisplayName = (String)result.Properties["displayname"][0];
    System.Console.WriteLine(DisplayName);
}
記得透過 DirectorySearcher.Filter 指定搜尋 SAMAccountName 鍵值;回傳的結果陣列中 displayname 則是使用者登入 AD 後顯示名稱。