PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

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 649. Zend_Auth Adapter for OpenID


<?php
class OpenIdAdapter implements Zend_Auth_Adapter_Interface {
    private 
$_id null;

    public function 
__construct($id null) {
        
$this->_id $id;
    }

    public function 
authenticate() {
        
$id $this->_id;
        if (!empty(
$id)) {
            
$consumer = new Zend_OpenId_Consumer();
            if (!
$consumer->login($id)) {
                
$ret false;
                
$msg "Authentication failed.";
            }
        } else {
            
$consumer = new Zend_OpenId_Consumer();
            if (
$consumer->verify($_GET$id)) {
                
$ret true;
                
$msg "Authentication successful";
            } else {
                
$ret false;
                
$msg "Authentication failed";
            }
        }
        return new 
Zend_Auth_Result($ret$id, array($msg));
    }
}

$status "";
$auth Zend_Auth::getInstance();
if ((isset(
$_POST['openid_action']) &&
     
$_POST['openid_action'] == "login" &&
     !empty(
$_POST['openid_identifier'])) ||
    isset(
$_GET['openid_mode'])) {
    
$adapter = new OpenIdAdapter(@$_POST['openid_identifier']);
    
$result $auth->authenticate($adapter);
    if (
$result->isValid()) {
        
Zend_OpenId::redirect(Zend_OpenId::selfURL());
    } else {
        
$auth->clearIdentity();
        foreach (
$result->getMessages() as $message) {
            
$status .= "$message<br>\n";
        }
    }
} else if (
$auth->hasIdentity()) {
    if (isset(
$_POST['openid_action']) &&
        
$_POST['openid_action'] == "logout") {
        
$auth->clearIdentity();
    } else {
        
$status "You are logged in as " $auth->getIdentity() . "<br>\n";
    }
}
?>
<html><body>
<?php echo htmlspecialchars($status);?>
<form method="post"><fieldset>
<legend>OpenID Login</legend>
<input type="text" name="openid_identifier" value="">
<input type="submit" name="openid_action" value="login">
<input type="submit" name="openid_action" value="logout">
</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.

Zend Framework