1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.openid.consumer">
4 <title>Zend_OpenId_Consumer Basics</title>
7 <classname>Zend_OpenId_Consumer</classname> can be used to implement OpenID
8 authentication for web sites.
11 <sect2 id="zend.openid.consumer.authentication">
12 <title>OpenID Authentication</title>
15 From a web site developer's point of view, the OpenID authentication
16 process consists of three steps:
22 Show OpenID authentication form
28 Accept OpenID identity and pass it to the OpenID provider
34 Verify response from the OpenID provider
40 The OpenID authentication protocol actually requires more
41 steps, but many of them are encapsulated inside
42 <classname>Zend_OpenId_Consumer</classname> and are therefore transparent to the
47 The end user initiates the OpenID authentication process by
48 submitting his or her identification credentials with the appropriate form.
49 The following example shows a simple form that accepts an OpenID
50 identifier. Note that the example only demonstrates a login.
53 <example id="zend.openid.consumer.example-1">
54 <title>The Simple OpenID Login form</title>
56 <programlisting language="php"><![CDATA[
58 <form method="post" action="example-1_2.php"><fieldset>
59 <legend>OpenID Login</legend>
60 <input type="text" name="openid_identifier">
61 <input type="submit" name="openid_action" value="login">
62 </fieldset></form></body></html>
67 This form passes the OpenID identity on submission to the following
68 <acronym>PHP</acronym> script that performs the second step of authentication. The
69 <acronym>PHP</acronym> script need only call the
70 <methodname>Zend_OpenId_Consumer::login()</methodname> method in this step. The first
71 argument of this method is an accepted OpenID identity, and the second is the
72 <acronym>URL</acronym> of a script that handles the third and last step of
76 <example id="zend.openid.consumer.example-1_2">
77 <title>The Authentication Request Handler</title>
79 <programlisting language="php"><![CDATA[
80 $consumer = new Zend_OpenId_Consumer();
81 if (!$consumer->login($_POST['openid_identifier'], 'example-1_3.php')) {
82 die("OpenID login failed.");
88 The <methodname>Zend_OpenId_Consumer::login()</methodname> method performs discovery on
89 a given identifier, and, if successful, obtains the address of the identity
90 provider and its local identifier. It then creates an association to the
91 given provider so that both the site and provider share a secret
92 that is used to sign the subsequent messages. Finally, it passes an
93 authentication request to the provider. This request redirects the
94 end user's web browser to an OpenID server site, where the user can
95 continue the authentication process.
99 An OpenID provider usually asks users for their password (if they
100 weren't previously logged-in), whether the user trusts this site and what
101 information may be returned to the site. These interactions are not
102 visible to the OpenID consumer, so it can not obtain the
103 user's password or other information that the user did not has not directed the
104 OpenID provider to share with it.
108 On success, <methodname>Zend_OpenId_Consumer::login()</methodname> does not
109 return, instead performing an <acronym>HTTP</acronym> redirection. However, if there is
110 an error it may return <constant>FALSE</constant>. Errors may occur due to an invalid
111 identity, unresponsive provider, communication error, etc.
115 The third step of authentication is initiated by the response from the
116 OpenID provider, after it has authenticated the user's password.
117 This response is passed indirectly, as an <acronym>HTTP</acronym> redirection using the
118 end user's web browser. The consumer must now simply check
119 that this response is valid.
122 <example id="zend.openid.consumer.example-1_3">
123 <title>The Authentication Response Verifier</title>
125 <programlisting language="php"><![CDATA[
126 $consumer = new Zend_OpenId_Consumer();
127 if ($consumer->verify($_GET, $id)) {
128 echo "VALID " . htmlspecialchars($id);
130 echo "INVALID " . htmlspecialchars($id);
136 This check is performed using the <classname>Zend_OpenId_Consumer::verify</classname>
137 method, which takes an array of
138 the <acronym>HTTP</acronym> request's arguments and checks that this response is
139 properly signed by the OpenID provider. It may assign
140 the claimed OpenID identity that was entered by end user in the
141 first step using a second, optional argument.
145 <sect2 id="zend.openid.consumer.combine">
146 <title>Combining all Steps in One Page</title>
149 The following example combines all three steps in one script. It doesn't
150 provide any new functionality. The advantage of using just one script is that
151 the developer need not specify <acronym>URL</acronym>'s for a script to handle the next
152 step. By default, all steps use the same <acronym>URL</acronym>. However, the script now
153 includes some dispatch code to execute the appropriate code for each step of
157 <example id="zend.openid.consumer.example-2">
158 <title>The Complete OpenID Login Script</title>
160 <programlisting language="php"><![CDATA[
163 if (isset($_POST['openid_action']) &&
164 $_POST['openid_action'] == "login" &&
165 !empty($_POST['openid_identifier'])) {
167 $consumer = new Zend_OpenId_Consumer();
168 if (!$consumer->login($_POST['openid_identifier'])) {
169 $status = "OpenID login failed.";
171 } else if (isset($_GET['openid_mode'])) {
172 if ($_GET['openid_mode'] == "id_res") {
173 $consumer = new Zend_OpenId_Consumer();
174 if ($consumer->verify($_GET, $id)) {
175 $status = "VALID " . htmlspecialchars($id);
177 $status = "INVALID " . htmlspecialchars($id);
179 } else if ($_GET['openid_mode'] == "cancel") {
180 $status = "CANCELLED";
185 <?php echo "$status<br>" ?>
188 <legend>OpenID Login</legend>
189 <input type="text" name="openid_identifier" value=""/>
190 <input type="submit" name="openid_action" value="login"/>
198 In addition, this code differentiates between cancelled and invalid
199 authentication responses. The provider returns a cancelled response
200 if the identity provider is not aware of the supplied identity, the user
201 is not logged in, or the user doesn't trust the site. An invalid response indicates
202 that the response is not conformant to the OpenID protocol or is incorrectly signed.
206 <sect2 id="zend.openid.consumer.realm">
207 <title>Consumer Realm</title>
210 When an OpenID-enabled site passes authentication requests to a
211 provider, it identifies itself with a realm <acronym>URL</acronym>. This
212 <acronym>URL</acronym> may be considered a root of a trusted site. If the user trusts
213 the realm <acronym>URL</acronym>, he or she should also trust matched and subsequent
214 <acronym>URL</acronym>s.
218 By default, the realm <acronym>URL</acronym> is automatically set to the
219 <acronym>URL</acronym> of the directory in which the login script resides. This default
220 value is useful for most, but not all, cases. Sometimes an entire domain, and not a
221 directory should be trusted. Or even a combination of several servers in one domain.
225 To override the default value, developers may pass the realm <acronym>URL</acronym> as a
226 third argument to the <classname>Zend_OpenId_Consumer::login</classname> method. In
227 the following example, a single interaction asks for trusted access to
231 <example id="zend.openid.consumer.example-3_2">
232 <title>Authentication Request for Specified Realm</title>
234 <programlisting language="php"><![CDATA[
235 $consumer = new Zend_OpenId_Consumer();
236 if (!$consumer->login($_POST['openid_identifier'],
238 'http://*.php.net/')) {
239 die("OpenID login failed.");
245 This example implements only the second step of authentication;
246 the first and third steps are similar to the examples above.
250 <sect2 id="zend.openid.consumer.check">
251 <title>Immediate Check</title>
254 In some cases, an application need only check if a user is already
255 logged in to a trusted OpenID server without any interaction with the
256 user. The <classname>Zend_OpenId_Consumer::check</classname> method does precisely
257 that. It is executed with the same arguments as
258 <classname>Zend_OpenId_Consumer::login</classname>, but it doesn't display any
259 OpenID server pages to the user. From the users point of view this process is
260 transparent, and it appears as though they never left the site. The third step
261 succeeds if the user is already logged in and trusted by the site, otherwise
265 <example id="zend.openid.consumer.example-4">
266 <title>Immediate Check without Interaction</title>
268 <programlisting language="php"><![CDATA[
269 $consumer = new Zend_OpenId_Consumer();
270 if (!$consumer->check($_POST['openid_identifier'], 'example-4_3.php')) {
271 die("OpenID login failed.");
277 This example implements only the second step of authentication;
278 the first and third steps are similar to the examples above.
282 <sect2 id="zend.openid.consumer.storage">
283 <title>Zend_OpenId_Consumer_Storage</title>
286 There are three steps in the OpenID authentication procedure, and each
287 step is performed by a separate <acronym>HTTP</acronym> request. To store information
288 between requests, <classname>Zend_OpenId_Consumer</classname> uses internal storage.
292 Developers do not necessarily have to be aware of this storage because by default
293 <classname>Zend_OpenId_Consumer</classname> uses file-based storage under the temporary
294 directory- similar to <acronym>PHP</acronym> sessions. However, this storage may be not
295 suitable in all cases. Some developers may want to store information in a database,
296 while others may need to use common storage suitable for server farms. Fortunately,
297 developers may easily replace the default storage with their own. To specify a custom
298 storage mechanism, one need only extend the
299 <classname>Zend_OpenId_Consumer_Storage</classname> class and pass this subclass to the
300 <classname>Zend_OpenId_Consumer</classname> constructor in the first argument.
304 The following example demonstrates a simple storage mechanism that uses
305 <classname>Zend_Db</classname> as its backend and exposes three groups of functions.
306 The first group contains functions for working with associations, while the second group
307 caches discovery information, and the third group can be used to check whether a
308 response is unique. This class can easily be used with existing or new databases; if the
309 required tables don't exist, it will create them.
312 <example id="zend.openid.consumer.example-5">
313 <title>Database Storage</title>
315 <programlisting language="php"><![CDATA[
316 class DbStorage extends Zend_OpenId_Consumer_Storage
319 private $_association_table;
320 private $_discovery_table;
321 private $_nonce_table;
323 // Pass in the Zend_Db_Adapter object and the names of the
325 public function __construct($db,
326 $association_table = "association",
327 $discovery_table = "discovery",
328 $nonce_table = "nonce")
331 $this->_association_table = $association_table;
332 $this->_discovery_table = $discovery_table;
333 $this->_nonce_table = $nonce_table;
334 $tables = $this->_db->listTables();
336 // If the associations table doesn't exist, create it
337 if (!in_array($association_table, $tables)) {
338 $this->_db->getConnection()->exec(
339 "create table $association_table (" .
340 " url varchar(256) not null primary key," .
341 " handle varchar(256) not null," .
342 " macFunc char(16) not null," .
343 " secret varchar(256) not null," .
344 " expires timestamp" .
348 // If the discovery table doesn't exist, create it
349 if (!in_array($discovery_table, $tables)) {
350 $this->_db->getConnection()->exec(
351 "create table $discovery_table (" .
352 " id varchar(256) not null primary key," .
353 " realId varchar(256) not null," .
354 " server varchar(256) not null," .
356 " expires timestamp" .
360 // If the nonce table doesn't exist, create it
361 if (!in_array($nonce_table, $tables)) {
362 $this->_db->getConnection()->exec(
363 "create table $nonce_table (" .
364 " nonce varchar(256) not null primary key," .
365 " created timestamp default current_timestamp" .
370 public function addAssociation($url,
376 $table = $this->_association_table;
377 $secret = base64_encode($secret);
378 $this->_db->insert($table, array(
381 'macFunc' => $macFunc,
383 'expires' => $expires,
388 public function getAssociation($url,
394 $table = $this->_association_table;
396 $table, $this->_db->quoteInto('expires < ?', time())
398 $select = $this-_db->select()
399 ->from($table, array('handle', 'macFunc', 'secret', 'expires'))
400 ->where('url = ?', $url);
401 $res = $this->_db->fetchRow($select);
403 if (is_array($res)) {
404 $handle = $res['handle'];
405 $macFunc = $res['macFunc'];
406 $secret = base64_decode($res['secret']);
407 $expires = $res['expires'];
413 public function getAssociationByHandle($handle,
419 $table = $this->_association_table;
421 $table, $this->_db->quoteInto('expires < ', time())
423 $select = $this->_db->select()
424 ->from($table, array('url', 'macFunc', 'secret', 'expires')
425 ->where('handle = ?', $handle);
426 $res = $select->fetchRow($select);
428 if (is_array($res)) {
430 $macFunc = $res['macFunc'];
431 $secret = base64_decode($res['secret']);
432 $expires = $res['expires'];
438 public function delAssociation($url)
440 $table = $this->_association_table;
441 $this->_db->query("delete from $table where url = '$url'");
445 public function addDiscoveryInfo($id,
451 $table = $this->_discovery_table;
452 $this->_db->insert($table, array(
456 'version' => $version,
457 'expires' => $expires,
463 public function getDiscoveryInfo($id,
469 $table = $this->_discovery_table;
470 $this->_db->delete($table, $this->quoteInto('expires < ?', time()));
471 $select = $this->_db->select()
472 ->from($table, array('realId', 'server', 'version', 'expires'))
473 ->where('id = ?', $id);
474 $res = $this->_db->fetchRow($select);
476 if (is_array($res)) {
477 $realId = $res['realId'];
478 $server = $res['server'];
479 $version = $res['version'];
480 $expires = $res['expires'];
486 public function delDiscoveryInfo($id)
488 $table = $this->_discovery_table;
489 $this->_db->delete($table, $this->_db->quoteInto('id = ?', $id));
493 public function isUniqueNonce($nonce)
495 $table = $this->_nonce_table;
497 $ret = $this->_db->insert($table, array(
500 } catch (Zend_Db_Statement_Exception $e) {
506 public function purgeNonces($date=null)
511 $db = Zend_Db::factory('Pdo_Sqlite',
512 array('dbname'=>'/tmp/openid_consumer.db'));
513 $storage = new DbStorage($db);
514 $consumer = new Zend_OpenId_Consumer($storage);
519 This example doesn't list the OpenID authentication code itself, but this
520 code would be the same as that for other examples in this chapter.
525 <sect2 id="zend.openid.consumer.sreg">
526 <title>Simple Registration Extension</title>
529 In addition to authentication, the OpenID standard can be used for
530 lightweight profile exchange to make information about a user portable across multiple
531 sites. This feature is not covered by the OpenID authentication specification, but by
532 the OpenID Simple Registration Extension protocol. This protocol allows OpenID-enabled
533 sites to ask for information about end users from OpenID providers. Such information may
540 <emphasis>nickname</emphasis>
541 - any UTF-8 string that the end user uses as a nickname
547 <emphasis>email</emphasis>
548 - the email address of the user as specified in section 3.4.1
555 <emphasis>fullname</emphasis>
556 - a UTF-8 string representation of the user's full name
562 <emphasis>dob</emphasis>
563 - the user's date of birth in the format 'YYYY-MM-DD'. Any values whose
564 representation uses fewer than the specified number of digits in this format
565 should be zero-padded. In other words, the length of this value must always be
566 10. If the end user does not want to reveal any particular
567 part of this value (i.e., year, month or day), it must be set to zero. For
568 example, if the user wants to specify that his date of birth falls in 1980,
569 but not specify the month or day, the value returned should be '1980-00-00'.
575 <emphasis>gender</emphasis>
576 - the user's gender: "M" for male, "F" for female
582 <emphasis>postcode</emphasis>
583 - a UTF-8 string that conforms to the postal system of the user's country
589 <emphasis>country</emphasis>
590 - the user's country of residence as specified by ISO3166
596 <emphasis>language</emphasis>
597 - the user's preferred language as specified by ISO639
603 <emphasis>timezone</emphasis>
604 - an <acronym>ASCII</acronym> string from a TimeZone database. For example,
605 "Europe/Paris" or "America/Los_Angeles".
611 An OpenID-enabled web site may ask for any combination of these
612 fields. It may also strictly require some information and allow users
613 to provide or hide additional information. The following example instantiates
614 the <classname>Zend_OpenId_Extension_Sreg</classname> class, requiring
615 a <emphasis>nickname</emphasis> and optionally requests
616 an <emphasis>email</emphasis> and a <emphasis>fullname</emphasis>.
619 <example id="zend.openid.consumer.example-6_2">
620 <title>Sending Requests with a Simple Registration Extension</title>
622 <programlisting language="php"><![CDATA[
623 $sreg = new Zend_OpenId_Extension_Sreg(array(
626 'fullname'=>false), null, 1.1);
627 $consumer = new Zend_OpenId_Consumer();
628 if (!$consumer->login($_POST['openid_identifier'],
632 die("OpenID login failed.");
638 As you can see, the <classname>Zend_OpenId_Extension_Sreg</classname>
639 constructor accepts an array of OpenID fields. This array has the names of
640 fields as indexes to a flag indicating whether the field is required;
641 <constant>TRUE</constant> means the field is required and
642 <constant>FALSE</constant> means the field is optional. The
643 <classname>Zend_OpenId_Consumer::login</classname> method accepts an extension or an
644 array of extensions as its fourth argument.
648 On the third step of authentication, the
649 <classname>Zend_OpenId_Extension_Sreg</classname> object should be passed to
650 <classname>Zend_OpenId_Consumer::verify</classname>. Then on successful authentication
651 the <classname>Zend_OpenId_Extension_Sreg::getProperties</classname> method will return
652 an associative array of requested fields.
655 <example id="zend.openid.consumer.example-6_3">
656 <title>Verifying Responses with a Simple Registration Extension</title>
658 <programlisting language="php"><![CDATA[
659 $sreg = new Zend_OpenId_Extension_Sreg(array(
662 'fullname'=>false), null, 1.1);
663 $consumer = new Zend_OpenId_Consumer();
664 if ($consumer->verify($_GET, $id, $sreg)) {
665 echo "VALID " . htmlspecialchars($id) ."<br>\n";
666 $data = $sreg->getProperties();
667 if (isset($data['nickname'])) {
668 echo "nickname: " . htmlspecialchars($data['nickname']) . "<br>\n";
670 if (isset($data['email'])) {
671 echo "email: " . htmlspecialchars($data['email']) . "<br>\n";
673 if (isset($data['fullname'])) {
674 echo "fullname: " . htmlspecialchars($data['fullname']) . "<br>\n";
677 echo "INVALID " . htmlspecialchars($id);
683 If the <classname>Zend_OpenId_Extension_Sreg</classname> object was created without any
684 arguments, the user code should check for the existence of the required
685 data itself. However, if the object is created with the same list of
686 required fields as on the second step, it will automatically check for the existence
687 of required data. In this case, <classname>Zend_OpenId_Consumer::verify</classname>
688 will return <constant>FALSE</constant> if any of the required fields are
693 <classname>Zend_OpenId_Extension_Sreg</classname> uses version
694 1.0 by default, because the specification for version 1.1 is not yet finalized.
695 However, some libraries don't fully support version 1.0. For example,
696 www.myopenid.com requires an SREG namespace in requests which is only
697 available in 1.1. To work with such a server, you must explicitly set the version to
698 1.1 in the <classname>Zend_OpenId_Extension_Sreg</classname> constructor.
702 The second argument of the <classname>Zend_OpenId_Extension_Sreg</classname>
703 constructor is a policy <acronym>URL</acronym>, that should be provided to the user by
704 the identity provider.
708 <sect2 id="zend.openid.consumer.auth">
709 <title>Integration with Zend_Auth</title>
712 Zend Framework provides a special class to support user
713 authentication: <classname>Zend_Auth</classname>. This class can be used together
714 with <classname>Zend_OpenId_Consumer</classname>. The following example shows how
715 <code>OpenIdAdapter</code> implements
716 the <classname>Zend_Auth_Adapter_Interface</classname> with the
717 <code>authenticate</code> method. This performs an authentication query and
722 The big difference between this adapter and existing ones, is that
723 it works on two <acronym>HTTP</acronym> requests and includes a dispatch code to perform
724 the second or third step of OpenID authentication.
727 <example id="zend.openid.consumer.example-7">
728 <title>Zend_Auth Adapter for OpenID</title>
730 <programlisting language="php"><![CDATA[
732 class OpenIdAdapter implements Zend_Auth_Adapter_Interface {
735 public function __construct($id = null) {
739 public function authenticate() {
742 $consumer = new Zend_OpenId_Consumer();
743 if (!$consumer->login($id)) {
745 $msg = "Authentication failed.";
748 $consumer = new Zend_OpenId_Consumer();
749 if ($consumer->verify($_GET, $id)) {
751 $msg = "Authentication successful";
754 $msg = "Authentication failed";
757 return new Zend_Auth_Result($ret, $id, array($msg));
762 $auth = Zend_Auth::getInstance();
763 if ((isset($_POST['openid_action']) &&
764 $_POST['openid_action'] == "login" &&
765 !empty($_POST['openid_identifier'])) ||
766 isset($_GET['openid_mode'])) {
767 $adapter = new OpenIdAdapter(@$_POST['openid_identifier']);
768 $result = $auth->authenticate($adapter);
769 if ($result->isValid()) {
770 Zend_OpenId::redirect(Zend_OpenId::selfURL());
772 $auth->clearIdentity();
773 foreach ($result->getMessages() as $message) {
774 $status .= "$message<br>\n";
777 } else if ($auth->hasIdentity()) {
778 if (isset($_POST['openid_action']) &&
779 $_POST['openid_action'] == "logout") {
780 $auth->clearIdentity();
782 $status = "You are logged in as " . $auth->getIdentity() . "<br>\n";
787 <?php echo htmlspecialchars($status);?>
788 <form method="post"><fieldset>
789 <legend>OpenID Login</legend>
790 <input type="text" name="openid_identifier" value="">
791 <input type="submit" name="openid_action" value="login">
792 <input type="submit" name="openid_action" value="logout">
793 </fieldset></form></body></html>
798 With <classname>Zend_Auth</classname> the end-user's identity is saved in the
799 session's data. It may be checked with <classname>Zend_Auth::hasIdentity</classname>
800 and <classname>Zend_Auth::getIdentity</classname>.
804 <sect2 id="zend.openid.consumer.mvc">
805 <title>Integration with Zend_Controller</title>
808 Finally a couple of words about integration into
809 Model-View-Controller applications: such Zend Framework applications are
810 implemented using the <classname>Zend_Controller</classname> class and they use
811 objects of the <classname>Zend_Controller_Response_Http</classname> class to prepare
812 <acronym>HTTP</acronym> responses and send them back to the user's web browser.
816 <classname>Zend_OpenId_Consumer</classname> doesn't provide any GUI
817 capabilities but it performs <acronym>HTTP</acronym> redirections on success of
818 <classname>Zend_OpenId_Consumer::login</classname> and
819 <classname>Zend_OpenId_Consumer::check</classname>. These redirections may work
820 incorrectly or not at all if some data was already sent to the web browser. To
821 properly perform <acronym>HTTP</acronym> redirection in <acronym>MVC</acronym> code the
822 real <classname>Zend_Controller_Response_Http</classname> should be sent to
823 <classname>Zend_OpenId_Consumer::login</classname> or
824 <classname>Zend_OpenId_Consumer::check</classname> as the last argument.