Chapter 3. Zym_Auth

Chapter 3. Zym_Auth

3.1. Adapters

3.1.1. Chain adapter

This adapter allows chaining of other authentication adapters to authenticate a user from multiple sources. Using this adapter can allows authenticating users from sources such as database, LDAP, and a remote service all in one go.

Setting up the chain is simple because you just add adapters to the chain with addAdapter(Zend_Auth_Adapter_Interface). The result is returned from the first successful adapter. A result returned from a failed authentication attempt is created by the chain adapter itself with a Zend_Auth_Result::FAILURE code, null identity, and an array of error messages from all failed adapters. Because it may be helpful to determine which adapter was successful for processing the user, the chain adapter provides the getLastSuccessfulAdapter() method which returns the successful adapter instance.

Example 3.1. Authenticating with multiple adapters

<?php
// Adapters to authenticate with
$dbAdapter = new Zend_Auth_Adapter_DbTable($db, 'users');
$dbAdapter->setIdentityColumn('username')
          ->setCredentialColumn('password')
          ->setIdentity('john')
          ->setCredential('xxx');
 
$ldapAdpater = new Zend_Auth_Adapter_Ldap(array(), 'john', 'xxx');
 
// Setup chain adapter
$chain = new Zym_Auth_Adapter_Chain();
$chain->addAdapter($dbAdapter)
      ->addAdapter($ldapAdpater);
 
// Authenticate with Zend_Auth to persist
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($chain);
 
// Did we pass?
if ($result->isValid()) {
    // Get the successful adapter
    $successAdapter = $chain->getLastSuccessfulAdapter();
    if ($successAdapter === $dbAdapter) {
        // Do something like store user info in session
    } else if ($successAdapter === $ldapAdpater) {
        // Do something like store user info in session
    }
}