Introduction

Zend_OpenId_Consumer Basics

Zend_OpenId_Consumer can be used to implement OpenID authentication for web sites.

OpenID Authentication

From a web site developer's point of view, the OpenID authentication process consists of three steps:

  1. Show OpenID authentication form

  2. Accept OpenID identity and pass it to the OpenID provider

  3. Verify response from the OpenID provider

The OpenID authentication protocol actually requires more steps, but many of them are encapsulated inside Zend_OpenId_Consumer and are therefore transparent to the developer.

The end user initiates the OpenID authentication process by submitting his or her identification credentials with the appropriate form. The following example shows a simple form that accepts an OpenID identifier. Note that the example only demonstrates a login.

Example #1 The Simple OpenID Login form

  1. <html><body>
  2. <form method="post" action="example-1_2.php"><fieldset>
  3. <legend>OpenID Login</legend>
  4. <input type="text" name="openid_identifier">
  5. <input type="submit" name="openid_action" value="login">
  6. </fieldset></form></body></html>

This form passes the OpenID identity on submission to the following PHP script that performs the second step of authentication. The PHP script need only call the Zend_OpenId_Consumer::login() method in this step. The first argument of this method is an accepted OpenID identity, and the second is the URL of a script that handles the third and last step of authentication.

Example #2 The Authentication Request Handler

  1. $consumer = new Zend_OpenId_Consumer();
  2. if (!$consumer->login($_POST['openid_identifier'], 'example-1_3.php')) {
  3.     die("OpenID login failed.");
  4. }

The Zend_OpenId_Consumer::login() method performs discovery on a given identifier, and, if successful, obtains the address of the identity provider and its local identifier. It then creates an association to the given provider so that both the site and provider share a secret that is used to sign the subsequent messages. Finally, it passes an authentication request to the provider. This request redirects the end user's web browser to an OpenID server site, where the user can continue the authentication process.

An OpenID provider usually asks users for their password (if they weren't previously logged-in), whether the user trusts this site and what information may be returned to the site. These interactions are not visible to the OpenID consumer, so it can not obtain the user's password or other information that the user did not has not directed the OpenID provider to share with it.

On success, Zend_OpenId_Consumer::login() does not return, instead performing an HTTP redirection. However, if there is an error it may return FALSE. Errors may occur due to an invalid identity, unresponsive provider, communication error, etc.

The third step of authentication is initiated by the response from the OpenID provider, after it has authenticated the user's password. This response is passed indirectly, as an HTTP redirection using the end user's web browser. The consumer must now simply check that this response is valid.

Example #3 The Authentication Response Verifier

  1. $consumer = new Zend_OpenId_Consumer();
  2. if ($consumer->verify($_GET, $id)) {
  3.     echo "VALID " . htmlspecialchars($id);
  4. } else {
  5.     echo "INVALID " . htmlspecialchars($id);
  6. }

This check is performed using the Zend_OpenId_Consumer::verify method, which takes an array of the HTTP request's arguments and checks that this response is properly signed by the OpenID provider. It may assign the claimed OpenID identity that was entered by end user in the first step using a second, optional argument.

Combining all Steps in One Page

The following example combines all three steps in one script. It doesn't provide any new functionality. The advantage of using just one script is that the developer need not specify URL's for a script to handle the next step. By default, all steps use the same URL. However, the script now includes some dispatch code to execute the appropriate code for each step of authentication.

Example #4 The Complete OpenID Login Script

  1. <?php
  2. $status = "";
  3. if (isset($_POST['openid_action']) &&
  4.     $_POST['openid_action'] == "login" &&
  5.     !empty($_POST['openid_identifier'])) {
  6.  
  7.     $consumer = new Zend_OpenId_Consumer();
  8.     if (!$consumer->login($_POST['openid_identifier'])) {
  9.         $status = "OpenID login failed.";
  10.     }
  11. } else if (isset($_GET['openid_mode'])) {
  12.     if ($_GET['openid_mode'] == "id_res") {
  13.         $consumer = new Zend_OpenId_Consumer();
  14.         if ($consumer->verify($_GET, $id)) {
  15.             $status = "VALID " . htmlspecialchars($id);
  16.         } else {
  17.             $status = "INVALID " . htmlspecialchars($id);
  18.         }
  19.     } else if ($_GET['openid_mode'] == "cancel") {
  20.         $status = "CANCELLED";
  21.     }
  22. }
  23. ?>
  24. <html><body>
  25. <?php echo "$status<br>" ?>
  26. <form method="post">
  27. <fieldset>
  28. <legend>OpenID Login</legend>
  29. <input type="text" name="openid_identifier" value=""/>
  30. <input type="submit" name="openid_action" value="login"/>
  31. </fieldset>
  32. </form>
  33. </body></html>

In addition, this code differentiates between cancelled and invalid authentication responses. The provider returns a cancelled response if the identity provider is not aware of the supplied identity, the user is not logged in, or the user doesn't trust the site. An invalid response indicates that the response is not conformant to the OpenID protocol or is incorrectly signed.

Consumer Realm

When an OpenID-enabled site passes authentication requests to a provider, it identifies itself with a realm URL. This URL may be considered a root of a trusted site. If the user trusts the realm URL, he or she should also trust matched and subsequent URLs.

By default, the realm URL is automatically set to the URL of the directory in which the login script resides. This default value is useful for most, but not all, cases. Sometimes an entire domain, and not a directory should be trusted. Or even a combination of several servers in one domain.

To override the default value, developers may pass the realm URL as a third argument to the Zend_OpenId_Consumer::login method. In the following example, a single interaction asks for trusted access to all php.net sites.

Example #5 Authentication Request for Specified Realm

  1. $consumer = new Zend_OpenId_Consumer();
  2. if (!$consumer->login($_POST['openid_identifier'],
  3.                       'example-3_3.php',
  4.                       'http://*.php.net/')) {
  5.     die("OpenID login failed.");
  6. }

This example implements only the second step of authentication; the first and third steps are similar to the examples above.

Immediate Check

In some cases, an application need only check if a user is already logged in to a trusted OpenID server without any interaction with the user. The Zend_OpenId_Consumer::check method does precisely that. It is executed with the same arguments as Zend_OpenId_Consumer::login, but it doesn't display any OpenID server pages to the user. From the users point of view this process is transparent, and it appears as though they never left the site. The third step succeeds if the user is already logged in and trusted by the site, otherwise it will fail.

Example #6 Immediate Check without Interaction

  1. $consumer = new Zend_OpenId_Consumer();
  2. if (!$consumer->check($_POST['openid_identifier'], 'example-4_3.php')) {
  3.     die("OpenID login failed.");
  4. }

This example implements only the second step of authentication; the first and third steps are similar to the examples above.

Zend_OpenId_Consumer_Storage

There are three steps in the OpenID authentication procedure, and each step is performed by a separate HTTP request. To store information between requests, Zend_OpenId_Consumer uses internal storage.

Developers do not necessarily have to be aware of this storage because by default Zend_OpenId_Consumer uses file-based storage under the temporary directory- similar to PHP sessions. However, this storage may be not suitable in all cases. Some developers may want to store information in a database, while others may need to use common storage suitable for server farms. Fortunately, developers may easily replace the default storage with their own. To specify a custom storage mechanism, one need only extend the Zend_OpenId_Consumer_Storage class and pass this subclass to the Zend_OpenId_Consumer constructor in the first argument.

The following example demonstrates a simple storage mechanism that uses Zend_Db as its backend and exposes three groups of functions. The first group contains functions for working with associations, while the second group caches discovery information, and the third group can be used to check whether a response is unique. This class can easily be used with existing or new databases; if the required tables don't exist, it will create them.

Example #7 Database Storage

  1. class DbStorage extends Zend_OpenId_Consumer_Storage
  2. {
  3.     private $_db;
  4.     private $_association_table;
  5.     private $_discovery_table;
  6.     private $_nonce_table;
  7.  
  8.     // Pass in the Zend_Db_Adapter object and the names of the
  9.     // required tables
  10.     public function __construct($db,
  11.                                 $association_table = "association",
  12.                                 $discovery_table = "discovery",
  13.                                 $nonce_table = "nonce")
  14.     {
  15.         $this->_db = $db;
  16.         $this->_association_table = $association_table;
  17.         $this->_discovery_table = $discovery_table;
  18.         $this->_nonce_table = $nonce_table;
  19.         $tables = $this->_db->listTables();
  20.  
  21.         // If the associations table doesn't exist, create it
  22.         if (!in_array($association_table, $tables)) {
  23.             $this->_db->getConnection()->exec(
  24.                 "create table $association_table (" .
  25.                 " url     varchar(256) not null primary key," .
  26.                 " handle  varchar(256) not null," .
  27.                 " macFunc char(16) not null," .
  28.                 " secret  varchar(256) not null," .
  29.                 " expires timestamp" .
  30.                 ")");
  31.         }
  32.  
  33.         // If the discovery table doesn't exist, create it
  34.         if (!in_array($discovery_table, $tables)) {
  35.             $this->_db->getConnection()->exec(
  36.                 "create table $discovery_table (" .
  37.                 " id      varchar(256) not null primary key," .
  38.                 " realId  varchar(256) not null," .
  39.                 " server  varchar(256) not null," .
  40.                 " version float," .
  41.                 " expires timestamp" .
  42.                 ")");
  43.         }
  44.  
  45.         // If the nonce table doesn't exist, create it
  46.         if (!in_array($nonce_table, $tables)) {
  47.             $this->_db->getConnection()->exec(
  48.                 "create table $nonce_table (" .
  49.                 " nonce   varchar(256) not null primary key," .
  50.                 " created timestamp default current_timestamp" .
  51.                 ")");
  52.         }
  53.     }
  54.  
  55.     public function addAssociation($url,
  56.                                    $handle,
  57.                                    $macFunc,
  58.                                    $secret,
  59.                                    $expires)
  60.     {
  61.         $table = $this->_association_table;
  62.         $secret = base64_encode($secret);
  63.         $this->_db->insert($table, array(
  64.             'url'     => $url,
  65.             'handle'  => $handle,
  66.             'macFunc' => $macFunc,
  67.             'secret'  => $secret,
  68.             'expires' => $expires,
  69.         ));
  70.         return true;
  71.     }
  72.  
  73.     public function getAssociation($url,
  74.                                    &$handle,
  75.                                    &$macFunc,
  76.                                    &$secret,
  77.                                    &$expires)
  78.     {
  79.         $table = $this->_association_table;
  80.         $this->_db->delete(
  81.             $table, $this->_db->quoteInto('expires < ?', time())
  82.         );
  83.         $select = $this-_db->select()
  84.                 ->from($table, array('handle', 'macFunc', 'secret', 'expires'))
  85.                 ->where('url = ?', $url);
  86.         $res = $this->_db->fetchRow($select);
  87.  
  88.         if (is_array($res)) {
  89.             $handle  = $res['handle'];
  90.             $macFunc = $res['macFunc'];
  91.             $secret  = base64_decode($res['secret']);
  92.             $expires = $res['expires'];
  93.             return true;
  94.         }
  95.         return false;
  96.     }
  97.  
  98.     public function getAssociationByHandle($handle,
  99.                                            &$url,
  100.                                            &$macFunc,
  101.                                            &$secret,
  102.                                            &$expires)
  103.     {
  104.         $table = $this->_association_table;
  105.         $this->_db->delete(
  106.             $table, $this->_db->quoteInto('expires < ', time())
  107.         );
  108.         $select = $this->_db->select()
  109.                 ->from($table, array('url', 'macFunc', 'secret', 'expires')
  110.                 ->where('handle = ?', $handle);
  111.         $res = $select->fetchRow($select);
  112.  
  113.         if (is_array($res)) {
  114.             $url     = $res['url'];
  115.             $macFunc = $res['macFunc'];
  116.             $secret  = base64_decode($res['secret']);
  117.             $expires = $res['expires'];
  118.             return true;
  119.         }
  120.         return false;
  121.     }
  122.  
  123.     public function delAssociation($url)
  124.     {
  125.         $table = $this->_association_table;
  126.         $this->_db->query("delete from $table where url = '$url'");
  127.         return true;
  128.     }
  129.  
  130.     public function addDiscoveryInfo($id,
  131.                                      $realId,
  132.                                      $server,
  133.                                      $version,
  134.                                      $expires)
  135.     {
  136.         $table = $this->_discovery_table;
  137.         $this->_db->insert($table, array(
  138.             'id'      => $id,
  139.             'realId'  => $realId,
  140.             'server'  => $server,
  141.             'version' => $version,
  142.             'expires' => $expires,
  143.         ));
  144.  
  145.         return true;
  146.     }
  147.  
  148.     public function getDiscoveryInfo($id,
  149.                                      &$realId,
  150.                                      &$server,
  151.                                      &$version,
  152.                                      &$expires)
  153.     {
  154.         $table = $this->_discovery_table;
  155.         $this->_db->delete($table, $this->quoteInto('expires < ?', time()));
  156.         $select = $this->_db->select()
  157.                 ->from($table, array('realId', 'server', 'version', 'expires'))
  158.                 ->where('id = ?', $id);
  159.         $res = $this->_db->fetchRow($select);
  160.  
  161.         if (is_array($res)) {
  162.             $realId  = $res['realId'];
  163.             $server  = $res['server'];
  164.             $version = $res['version'];
  165.             $expires = $res['expires'];
  166.             return true;
  167.         }
  168.         return false;
  169.     }
  170.  
  171.     public function delDiscoveryInfo($id)
  172.     {
  173.         $table = $this->_discovery_table;
  174.         $this->_db->delete($table, $this->_db->quoteInto('id = ?', $id));
  175.         return true;
  176.     }
  177.  
  178.     public function isUniqueNonce($nonce)
  179.     {
  180.         $table = $this->_nonce_table;
  181.         try {
  182.             $ret = $this->_db->insert($table, array(
  183.                 'nonce' => $nonce,
  184.             ));
  185.         } catch (Zend_Db_Statement_Exception $e) {
  186.             return false;
  187.         }
  188.         return true;
  189.     }
  190.  
  191.     public function purgeNonces($date=null)
  192.     {
  193.     }
  194. }
  195.  
  196. $db = Zend_Db::factory('Pdo_Sqlite',
  197.     array('dbname'=>'/tmp/openid_consumer.db'));
  198. $storage = new DbStorage($db);
  199. $consumer = new Zend_OpenId_Consumer($storage);

This example doesn't list the OpenID authentication code itself, but this code would be the same as that for other examples in this chapter. examples.

Simple Registration Extension

In addition to authentication, the OpenID standard can be used for lightweight profile exchange to make information about a user portable across multiple sites. This feature is not covered by the OpenID authentication specification, but by the OpenID Simple Registration Extension protocol. This protocol allows OpenID-enabled sites to ask for information about end users from OpenID providers. Such information may include:

  • nickname - any UTF-8 string that the end user uses as a nickname

  • email - the email address of the user as specified in section 3.4.1 of RFC2822

  • fullname - a UTF-8 string representation of the user's full name

  • dob - the user's date of birth in the format 'YYYY-MM-DD'. Any values whose representation uses fewer than the specified number of digits in this format should be zero-padded. In other words, the length of this value must always be 10. If the end user does not want to reveal any particular part of this value (i.e., year, month or day), it must be set to zero. For example, if the user wants to specify that his date of birth falls in 1980, but not specify the month or day, the value returned should be '1980-00-00'.

  • gender - the user's gender: "M" for male, "F" for female

  • postcode - a UTF-8 string that conforms to the postal system of the user's country

  • country - the user's country of residence as specified by ISO3166

  • language - the user's preferred language as specified by ISO639

  • timezone - an ASCII string from a TimeZone database. For example, "Europe/Paris" or "America/Los_Angeles".

An OpenID-enabled web site may ask for any combination of these fields. It may also strictly require some information and allow users to provide or hide additional information. The following example instantiates the Zend_OpenId_Extension_Sreg class, requiring a nickname and optionally requests an email and a fullname.

Example #8 Sending Requests with a Simple Registration Extension

  1. $sreg = new Zend_OpenId_Extension_Sreg(array(
  2.     'nickname'=>true,
  3.     'email'=>false,
  4.     'fullname'=>false), null, 1.1);
  5. $consumer = new Zend_OpenId_Consumer();
  6. if (!$consumer->login($_POST['openid_identifier'],
  7.                       'example-6_3.php',
  8.                       null,
  9.                       $sreg)) {
  10.     die("OpenID login failed.");
  11. }

As you can see, the Zend_OpenId_Extension_Sreg constructor accepts an array of OpenID fields. This array has the names of fields as indexes to a flag indicating whether the field is required; TRUE means the field is required and FALSE means the field is optional. The Zend_OpenId_Consumer::login method accepts an extension or an array of extensions as its fourth argument.

On the third step of authentication, the Zend_OpenId_Extension_Sreg object should be passed to Zend_OpenId_Consumer::verify. Then on successful authentication the Zend_OpenId_Extension_Sreg::getProperties method will return an associative array of requested fields.

Example #9 Verifying Responses with a Simple Registration Extension

  1. $sreg = new Zend_OpenId_Extension_Sreg(array(
  2.     'nickname'=>true,
  3.     'email'=>false,
  4.     'fullname'=>false), null, 1.1);
  5. $consumer = new Zend_OpenId_Consumer();
  6. if ($consumer->verify($_GET, $id, $sreg)) {
  7.     echo "VALID " . htmlspecialchars($id) ."<br>\n";
  8.     $data = $sreg->getProperties();
  9.     if (isset($data['nickname'])) {
  10.         echo "nickname: " . htmlspecialchars($data['nickname']) . "<br>\n";
  11.     }
  12.     if (isset($data['email'])) {
  13.         echo "email: " . htmlspecialchars($data['email']) . "<br>\n";
  14.     }
  15.     if (isset($data['fullname'])) {
  16.         echo "fullname: " . htmlspecialchars($data['fullname']) . "<br>\n";
  17.     }
  18. } else {
  19.     echo "INVALID " . htmlspecialchars($id);
  20. }

If the Zend_OpenId_Extension_Sreg object was created without any arguments, the user code should check for the existence of the required data itself. However, if the object is created with the same list of required fields as on the second step, it will automatically check for the existence of required data. In this case, Zend_OpenId_Consumer::verify will return FALSE if any of the required fields are missing.

Zend_OpenId_Extension_Sreg uses version 1.0 by default, because the specification for version 1.1 is not yet finalized. However, some libraries don't fully support version 1.0. For example, www.myopenid.com requires an SREG namespace in requests which is only available in 1.1. To work with such a server, you must explicitly set the version to 1.1 in the Zend_OpenId_Extension_Sreg constructor.

The second argument of the Zend_OpenId_Extension_Sreg constructor is a policy URL, that should be provided to the user by the identity provider.

Integration with Zend_Auth

Zend Framework provides a special class to support user authentication: Zend_Auth. This class can be used together with Zend_OpenId_Consumer. The following example shows how OpenIdAdapter implements the Zend_Auth_Adapter_Interface with the authenticate method. This performs an authentication query and verification.

The big difference between this adapter and existing ones, is that it works on two HTTP requests and includes a dispatch code to perform the second or third step of OpenID authentication.

Example #10 Zend_Auth Adapter for OpenID

  1. <?php
  2. class OpenIdAdapter implements Zend_Auth_Adapter_Interface {
  3.     private $_id = null;
  4.  
  5.     public function __construct($id = null) {
  6.         $this->_id = $id;
  7.     }
  8.  
  9.     public function authenticate() {
  10.         $id = $this->_id;
  11.         if (!empty($id)) {
  12.             $consumer = new Zend_OpenId_Consumer();
  13.             if (!$consumer->login($id)) {
  14.                 $ret = false;
  15.                 $msg = "Authentication failed.";
  16.             }
  17.         } else {
  18.             $consumer = new Zend_OpenId_Consumer();
  19.             if ($consumer->verify($_GET, $id)) {
  20.                 $ret = true;
  21.                 $msg = "Authentication successful";
  22.             } else {
  23.                 $ret = false;
  24.                 $msg = "Authentication failed";
  25.             }
  26.         }
  27.         return new Zend_Auth_Result($ret, $id, array($msg));
  28.     }
  29. }
  30.  
  31. $status = "";
  32. $auth = Zend_Auth::getInstance();
  33. if ((isset($_POST['openid_action']) &&
  34.      $_POST['openid_action'] == "login" &&
  35.      !empty($_POST['openid_identifier'])) ||
  36.     isset($_GET['openid_mode'])) {
  37.     $adapter = new OpenIdAdapter(@$_POST['openid_identifier']);
  38.     $result = $auth->authenticate($adapter);
  39.     if ($result->isValid()) {
  40.         Zend_OpenId::redirect(Zend_OpenId::selfURL());
  41.     } else {
  42.         $auth->clearIdentity();
  43.         foreach ($result->getMessages() as $message) {
  44.             $status .= "$message<br>\n";
  45.         }
  46.     }
  47. } else if ($auth->hasIdentity()) {
  48.     if (isset($_POST['openid_action']) &&
  49.         $_POST['openid_action'] == "logout") {
  50.         $auth->clearIdentity();
  51.     } else {
  52.         $status = "You are logged in as " . $auth->getIdentity() . "<br>\n";
  53.     }
  54. }
  55. ?>
  56. <html><body>
  57. <?php echo htmlspecialchars($status);?>
  58. <form method="post"><fieldset>
  59. <legend>OpenID Login</legend>
  60. <input type="text" name="openid_identifier" value="">
  61. <input type="submit" name="openid_action" value="login">
  62. <input type="submit" name="openid_action" value="logout">
  63. </fieldset></form></body></html>

With Zend_Auth the end-user's identity is saved in the session's data. It may be checked with Zend_Auth::hasIdentity and Zend_Auth::getIdentity.

Integration with Zend_Controller

Finally a couple of words about integration into Model-View-Controller applications: such Zend Framework applications are implemented using the Zend_Controller class and they use objects of the Zend_Controller_Response_Http class to prepare HTTP responses and send them back to the user's web browser.

Zend_OpenId_Consumer doesn't provide any GUI capabilities but it performs HTTP redirections on success of Zend_OpenId_Consumer::login and Zend_OpenId_Consumer::check. These redirections may work incorrectly or not at all if some data was already sent to the web browser. To properly perform HTTP redirection in MVC code the real Zend_Controller_Response_Http should be sent to Zend_OpenId_Consumer::login or Zend_OpenId_Consumer::check as the last argument.


Introduction