Previous Next

Introduction

Note: Minimal Functionality

Currently this class is designed only to satisfy the limited functionality necessary for the Zend_Auth_Adapter_Ldap authentication adapter. Operations such as searching, creating, modifying or renaming entries in the directory are currently not supported and will be defined at a later time.

Zend_Ldap is a class for performing LDAP operations including but not limited to binding, searching and modifying entries in an LDAP directory.

Theory of Operation

This component currently consists of two classes, Zend_Ldap and Zend_Ldap_Exception. The Zend_Ldap class conceptually represents a binding to a single LDAP server. The parameters for binding may be provided explicitly or in the form of an options array.

Using the Zend_Ldap class depends on the type of LDAP server and is best summarized with some simple examples.

If you are using OpenLDAP, a simple example looks like the following (note that the bindRequiresDn option is important if you are not using AD):

$options = array(
    'host' => 's0.foo.net',
    'username' => 'CN=user1,DC=foo,DC=net',
    'password' => 'pass1',
    'bindRequiresDn' => true,
    'accountDomainName' => 'foo.net',
    'baseDn' => 'OU=Sales,DC=foo,DC=net',
);
$ldap = new Zend_Ldap($options);
$acctname = $ldap->getCanonicalAccountName('abaker',
                                           Zend_Ldap::ACCTNAME_FORM_DN);
echo "$acctname\n";

If you are using Microsoft AD a simple example is:

$options = array(
    'host' => 'dc1.w.net',
    'useStartTls' => true,
    'username' => 'user1@w.net',
    'password' => 'pass1',
    'accountDomainName' => 'w.net',
    'accountDomainNameShort' => 'W',
    'baseDn' => 'CN=Users,DC=w,DC=net',
);
$ldap = new Zend_Ldap($options);
$acctname = $ldap->getCanonicalAccountName('bcarter',
                                           Zend_Ldap::ACCTNAME_FORM_DN);
echo "$acctname\n";
Note that we use the getCanonicalAccountName() method to retrieve the account DN here only because that is what exercises the most of what little code is currently present in this class.

Automatic Username Canonicalization When Binding

If bind() is called with a non-DN username but bindRequiresDN is true and no username in DN form was supplied as an option, the bind will fail. However, if a username in DN form is supplied in the options array, Zend_Ldap will first bind with that username, retrieve the account DN for the username supplied to bind() and then re- bind with that DN.

This behavior is critical to Zend_Auth_Adapter_Ldap, which passes the username supplied by the user directly to bind().

The following example illustrates how the non-DN username 'abaker' can be used with bind():

$options = array(
        'host' => 's0.foo.net',
        'username' => 'CN=user1,DC=foo,DC=net',
        'password' => 'pass1',
        'bindRequiresDn' => true,
        'accountDomainName' => 'foo.net',
        'baseDn' => 'OU=Sales,DC=foo,DC=net',
);
$ldap = new Zend_Ldap($options);
$ldap->bind('abaker', 'moonbike55');
$acctname = $ldap->getCanonicalAccountName('abaker',
                                           Zend_Ldap::ACCTNAME_FORM_DN);
echo "$acctname\n";
The bind() call in this example sees that the username 'abaker' is not in DN form, finds bindRequiresDn is true, uses 'CN=user1,DC=foo,DC=net' and 'pass1' to bind, retrieves the DN for 'abaker', unbinds and then rebinds with the newly discovered 'CN=Alice Baker,OU=Sales,DC=foo,DC=net'.

Zend_Ldap Options

The Zend_Ldap component accepts an array of options either supplied to the constructor or through the setOptions() method. The permitted options are as follows:

Zend_Ldap Options
Name Description
host The default hostname of LDAP server if not supplied to connect() (also may be used when trying to canonicalize usernames in bind()).
port Default port of LDAP server if not supplied to connect().
useStartTls Whether or not the LDAP client should use TLS (aka SSLv2) encrypted transport. A value of true is strongly favored in production environments to prevent passwords from be transmitted in clear text. The default value is false, as servers frequently require that a certificate be installed separately after installation. The useSsl and useStartTls options are mutually exclusive. The useStartTls option should be favored over useSsl but not all servers support this newer mechanism.
useSsl Whether or not the LDAP client should use SSL encrypted transport. The useSsl and useStartTls options are mutually exclusive.
username The default credentials username. Some servers require that this be in DN form.
password The default credentials password (used only with username above).
bindRequiresDn If true, this instructs Zend_Ldap to retrieve the DN for the account used to bind if the username is not already in DN form. The default value is false.
baseDn The default base DN used for searching (e.g., for accounts). This option is required for most account related operations and should indicate the DN under which accounts are located.
accountCanonicalForm A small integer indicating the form to which account names should be canonicalized. See the Account Name Canonicalization section below.
accountDomainName The FQDN domain for which the target LDAP server is an authority (e.g., example.com).
accountDomainNameShort The 'short' domain for which the target LDAP server is an authority. This is usually used to specify the NetBIOS domain name for Windows networks but may also be used by non-AD servers.
accountFilterFormat The LDAP search filter used to search for accounts. This string is a » printf() style expression that must contain one '%s' to accommodate the username. The default value is '(&(objectClass=user)(sAMAccountName=%s))' unless bindRequiresDn is set to true, in which case the default is '(&(objectClass=posixAccount)(uid=%s))'. Users of custom schemas may need to change this option.
allowEmptyPassword Some LDAP servers can be configured to accept an empty string password as an anonymous bind. This behavior is almost always undesirable. For this reason, empty passwords are explicitly disallowed. Set this value to true to allow an empty string password to be submitted during the bind.
optReferrals If set to true, this option indicates to the LDAP client that referrals should be followed. The default value is false.

Account Name Canonicalization

The accountDomainName and accountDomainNameShort options are used for two purposes: (1) they facilitate multi-domain authentication and failover capability, and (2) they are also used to canonicalize usernames. Specifically, names are canonicalized to the form specified by the accountCanonicalForm option. This option may one of the following values:

accountCanonicalForm
Name Value Example
ACCTNAME_FORM_DN 1 CN=Alice Baker,CN=Users,DC=example,DC=com
ACCTNAME_FORM_USERNAME 2 abaker
ACCTNAME_FORM_BACKSLASH 3 EXAMPLE\abaker
ACCTNAME_FORM_PRINCIPAL 4 abaker@example.com

The default canonicalization depends on what account domain name options were supplied. If accountDomainNameShort was supplied, the default accountCanonicalForm value is ACCTNAME_FORM_BACKSLASH. Otherwise, if accountDomainName was supplied, the default is ACCTNAME_FORM_PRINCIPAL.

Account name canonicalization ensures that the string used to identify an account is consistent regardless of what was supplied to bind(). For example, if the user supplies an account name of abaker@example.com or just abaker and the accountCanonicalForm is set to 3, the resulting canonicalized name would be EXAMPLE\abaker.

Multi-domain Authentication and Failover

The Zend_Ldap component by itself makes no attempt to authenticate with multiple servers. However, Zend_Ldap is specifically designed to handle this scenario gracefully. The required technique is to simply iterate over an array of arrays of server options and attempt to bind with each server. As described above bind() will automatically canonicalize each name, so it does not matter if the user passes abaker@foo.net or W\bcarter or cdavis - the bind() method will only succeed if the credentials were successfully used in the bind.

Consider the following example that illustrates the technique required to implement multi-domain authentication and failover:

$acctname = 'W\\user2';
$password = 'pass2';

$multiOptions = array(
    'server1' => array(
        'host' => 's0.foo.net',
        'username' => 'CN=user1,DC=foo,DC=net',
        'password' => 'pass1',
        'bindRequiresDn' => true,
        'accountDomainName' => 'foo.net',
        'accountDomainNameShort' => 'FOO',
        'accountCanonicalForm' => 4, // ACCT_FORM_PRINCIPAL
        'baseDn' => 'OU=Sales,DC=foo,DC=net',
    ),
    'server2' => array(
        'host' => 'dc1.w.net',
        'useSsl' => true,
        'username' => 'user1@w.net',
        'password' => 'pass1',
        'accountDomainName' => 'w.net',
        'accountDomainNameShort' => 'W',
        'accountCanonicalForm' => 4, // ACCT_FORM_PRINCIPAL
        'baseDn' => 'CN=Users,DC=w,DC=net',
    ),
);

$ldap = new Zend_Ldap();

foreach ($multiOptions as $name => $options) {

    echo "Trying to bind using server options for '$name'\n";

    $ldap->setOptions($options);
    try {
        $ldap->bind($acctname, $password);
        $acctname = $ldap->getCanonicalAccountName($acctname);
        echo "SUCCESS: authenticated $acctname\n";
        return;
    } catch (Zend_Ldap_Exception $zle) {
        echo '  ' . $zle->getMessage() . "\n";
        if ($zle->getCode() === Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH) {
            continue;
        }
    }
}
If the bind fails for any reason, the next set of server options is tried.

The getCanonicalAccountName call gets the canonical account name that the application would presumably use to associate data with such as preferences. The accountCanonicalForm = 4 in all server options ensures that the canonical form is consistent regardless of which server was ultimately used.

The special LDAP_X_DOMAIN_MISMATCH exception occurs when an account name with a domain component was supplied (e.g., abaker@foo.net or FOO\abaker and not just abaker) but the domain component did not match either domain in the currently selected server options. This exception indicates that the server is not an authority for the account. In this case, the bind will not be performed, thereby eliminating unnecessary communication with the server. Note that the continue instruction has no effect in this example, but in practice for error handling and debugging purposes, you will probably want to check for LDAP_X_DOMAIN_MISMATCH as well as LDAP_NO_SUCH_OBJECT and LDAP_INVALID_CREDENTIALS.

The above code is very similar to code used within Zend_Auth_Adapter_Ldap. In fact, we recommend that you simply use that authentication adapter for multi-domain + failover LDAP based authentication (or copy the code).

Previous Next
Introduction to Zend Framework
Présentation
Installation
Zend_Acl
Introduction
Affiner les Contrôles d'Accès
Utilisation avancée
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Auth
Introduction
Authentification avec une table de base de données
Authentification "Digest"
Adaptateur d'authentification HTTP
LDAP Authentication
Authentification OpenID
Zend_Cache
Introduction
Aspect théorique
Les frontends Zend_Cache
Les backends Zend_Cache
Zend_Captcha
Introduction
Opération Captcha
Adaptateurs Captcha
Zend_Config
Introduction
Aspect théorique
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction à Getopt
Déclarer les règles Getopt
Extraire les options et les arguments
Configurer Zend_Console_Getopt
Zend_Controller
Zend_Controller - Démarrage rapide
Fondations de Zend_Controller
Le contrôleur frontal (Front Controller)
L'objet Requête
Routeur Standard
Le dispatcheur
Contrôleurs d'action
Aides d'action (Helper)
Objet de réponse
Plugins
Utilisation de conventions de dossiers modulaires
Exceptions avec MVC
Migrer depuis des versions précédentes
Zend_Currency
Introduction à Zend_Currency
How to work with currencies
Migrer depuis des versions antérieures
Zend_Date
Introduction
Aspect théorique
Méthodes de base
Zend_Date API Overview
Créer des dates
Constants for General Date Functions
Exemples concrets
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Relations Zend_Db_Table
Zend_Debug
Afficher des informations
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Les aides de vues Dojo
Les éléments de formulaire et les décorateurs Dojo
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Utiliser les exceptions
Zend_Feed
Introduction
Importer des flux
Obtenir des flux à partir de pages Web
Consommer un flux RSS
Consommer un flux Atom
Consommer une entrée Atom particulière
Modifier la structure du flux ou des entrées
Classes personnalisées pour les flux et entrées
Zend_File
Zend_File_Transfer
Validateurs pour Zend_File_Transfer
Filtres pour Zend_File_Transfer
Migrer à partir des versions précédentes
Zend_Filter
Introduction
Classes de filtre standards
Chaînes de filtrage
Écriture de filtres
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction to Gdata
Authentification par procédé AuthSub
Using the Book Search Data API
Authentification avec ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Utilisation des albums Web Picasa
Using the YouTube Data API
Attraper les exceptions Gdata
Zend_Http
Zend_Http_Client - Introduction
Zend_Http_Client - Utilisation avancée
Zend_Http_Client - Adaptateurs de connexion
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Utilisation de base
Objets JSON
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout - Démarrage rapide
Zend_Layout options de configuration
Zend_Layout, utilisation avancée
Zend_Ldap
Introduction
Zend_Loader
Charger les fichiers et les classes dynamiquement
Chargeur de Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrer à partir des versions précédentes
Zend_Log
Présentation
Rédacteurs (Writers)
Formateurs (mise en forme)
Filtres
Zend_Mail
Introduction
Envoyer des émail en utilisant SMTP
Envoyer plusieurs émail par connexion SMTP
Utiliser différents transports
Émail HTML
Fichiers joints
Ajouter des destinataires
Contrôler les limites MIME
Entêtes additionnelles
Jeux de caractères
Encodage
Authentification SMTP
Sécuriser les transports SMTP
Lire des émail
Zend_Measure
Introduction
Création d'une mesure
Récupérer des mesures
Manipuler des mesures
Types de mesures
Zend_Memory
Présentation
Manager de mémoire
Objet mémoire
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Utilisation
Configuration
Utilisation avancée
Zend_Pdf
Introduction.
Créer et charger des documents PDF
Sauvegarder les changement dans un document PDF
Les pages d'un document
Dessiner
Informations du document et métadonnées.
Exemple d'utilisation du module Zend_Pdf
Zend_ProgressBar
Zend_ProgressBar
Zend_Registry
Utiliser le registre
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Jeu de caractères
Extensibility
Agir avec Lucene Java
Avancé
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Usage basique
Utilisation avancée
Gestion générale de la session
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL
Auto découverte
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Utiliser Zend_TimeSync
Zend_Translate
Introduction
Adaptateurs pour Zend_Translate
Utiliser les adaptateurs de traduction
Migrer à partir des versions précédentes
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Classes de validation standard
Chaînes de validation
Écrire des validateurs
Zend_Version
Lire la version du Zend Framework
Zend_View
Introduction
Scripts de contrôleur
Scripts de vue
Aides de vue
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Configuration système requise par le Zend Framework
Version de PHP requise
Extensions PHP
Les composants du Zend Framework
Dépendances internes du Zend Framework
Convention de codage PHP du Zend Framework
Vue d'ensemble
Formatage des fichiers PHP
Conventions de nommage
Style de codage
Zend Framework Performance Guide
Introduction
Class Loading
Internationalisation (i18n) and Localisation (l10n)
View Rendering
Informations de copyright