Capítulo 3. Zend_Auth
Anterior |  | Próxima

## Capítulo 3. Zend_Auth

## 3.1. Introduction

Zend_Auth provides an API for authentication and includes concrete authentication adapters for common use case scenarios.

| Nota
Zend_Auth currently includes a digest authentication adapter as a simple proof-of-concept for the design. Additional adapters are planned for development. Interested in using a particular adapter? Your voting for an adapter and contributions are most welcome!

Zend_Auth is concerned only with authentication and not with authorization. Authentication is loosely defined as determining whether an entity actually is what it purports to be (i.e., identification), based on some set of credentials. Authorization, the process of deciding whether to allow an entity access to, or to perform operations upon, other entities is outside the scope of Zend_Auth. For more information about authorization and access control with the Zend Framework, please see Zend_Acl.

### 3.1.1. Adapters

A Zend_Auth adapter is used to authenticate against a particular type of authentication service, such as LDAP, RDBMS, or file-based storage. Different adapters are likely to have vastly different options and behaviors, but some basic things are common among adapters. For example, accepting authentication credentials (including a purported identity), authenticating, and returning some result are common to Zend_Auth adapter.

Each Zend_Auth authentication adapter class implements `Zend_Auth_Adapter_Interface`. This interface defines one method, `authenticate()`, that an adapter class implements for authentication purposes. Each adapter class must be prepared prior to calling `authenticate()`. This means that each adapter provides the ability to set up credentials (e.g., username and password) and to define values for adapter-specific options, such as database connection settings for a database table adapter.

The following is an example authentication adapter that requires a username and password to be set for authentication. Other details, such as how the authentication service is queried, have been omitted for brevity:

    <?php
    require_once 'Zend/Auth/Adapter/Interface.php';

    class MyAuthAdapter implements Zend_Auth_Adapter_Interface
    {
        /**
         * Sets username and password for authentication
         *
         * @return void
         */
        public function __construct($username, $password)
        {
            // ...
        }

        /**
         * Performs an authentication attempt
         *
         * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
         * @return Zend_Auth_Result
         */
        public function authenticate()
        {
            // ...
        }
    }

As indicated in its docblock, `authenticate()` must return an instance of `Zend_Auth_Result` (or a class derived from `Zend_Auth_Result`). If for some reason performing an authentication query is impossible, `authenticate()` should throw an exception that derives from `Zend_Auth_Adapter_Exception`.

### 3.1.2. Results

Zend_Auth adapters return an instance of `Zend_Auth_Result` with `authenticate()` in order to represent the results of an authentication attempt. Adapters populate the `Zend_Auth_Result` object upon construction, so that the following three methods provide a basic set of operations common to the results of Zend_Auth adapters:

- `isValid()` - returns true if and only if the result represents a successful authentication attempt

- `getIdentity()` - returns the identity of the authentication attempt

- `getMessages()` - returns an array of messages regarding a failed authentication attempt

### 3.1.3. Identity Persistence

Authenticating a request that includes authentication credentials is useful per se, but it is also important to support maintaining the authenticated identity without having to present the authentication credentials with each request.

HTTP is a stateless protocol, however, and techniques such as cookies and sessions have been developed in order to facilitate maintaining state across multiple requests in server-side web applications. Zend_Session is used by default within Zend_Auth to provide persistent storage of the identity from a successful authentication attempt using the PHP session.

Upon a successful authentication attempt, `Zend_Auth::authenticate()` stores the identity from the authentication result into persistent storage. By default, `Zend_Auth` uses a storage class based on Zend_Session. The storage class may be changed by providing a different storage object to `Zend_Auth::setStorage()`.

If automatic persistent storage of the identity is not appropriate for a particular use case, then developers may forgo using the `Zend_Auth` class altogether, instead using an adapter class directly.

### 3.1.4. Using Zend_Auth

There are two provided ways to use Zend_Auth adapters:

1. indirectly, through `Zend_Auth::authenticate()`

2. directly, through the adapter's `authenticate()` method

The following example illustrates how to use a Zend_Auth adapter indirectly, through the use of the `Zend_Auth` class:

    <?php
    // Get a reference to the Singleton instance of Zend_Auth
    require_once 'Zend/Auth.php';
    $auth = Zend_Auth::getInstance();

    // Set up the authentication adapter
    $authAdapter = new MyAuthAdapter($username, $password);

    // Attempt authentication, saving the result
    $result = $auth->authenticate($authAdapter);

    if (!$result->isValid()) {
        // Authentication failed; print the reasons why
        foreach ($result->getMessages() as $message) {
            echo "$message\n";
        }
    } else {
        // Authentication succeeded; the identity ($username) is stored in the session
        // $result->getIdentity() === $auth->getIdentity()
        // $result->getIdentity() === $username
    }

Once authentication has been attempted in a request, as in the above example, it is a simple matter to check whether a successfully authenticated identity exists:

    <?php
    $auth = Zend_Auth::getInstance();
    if ($auth->hasIdentity()) {
        // Identity exists; get it
        $identity = $auth->getIdentity();
    }

To remove an identity from persistent storage, simply use the `clearIdentity()` method. This typically would be used for implementing an application "logout" operation:

    <?php
    Zend_Auth::getInstance()->clearIdentity();

When the automatic use of persistent storage is inappropriate for a particular use case, a developer may simply bypass the use of the `Zend_Auth` class, using an adapter class directly. Direct use of an adapter class involves configuring and preparing an adapter object and then calling its `authenticate()` method. Adapter-specific details are discussed in the documentation for each adapter. The following example directly utilizes `MyAuthAdapter`:

    <?php
    // Set up the authentication adapter
    $authAdapter = new MyAuthAdapter($username, $password);

    // Attempt authentication, saving the result
    $result = $authAdapter->authenticate();

    if (!$result->isValid()) {
        // Authentication failed; print the reasons why
        foreach ($result->getMessages() as $message) {
            echo "$message\n";
        }
    } else {
        // Authentication succeeded
        // $result->getIdentity() === $username
    }

Anterior |  | Próxima
2.3. Advanced Use | Principal | 3.2. Digest Authentication