Zend Framework - Authentication



Authentication is one of the most significant and must-have feature in any web application. Zend Framework provides a separate component to handle authentication, which is called as the zend-authentication.

Install an Authentication Component

The authentication component can be installed using the following Composer command.

composer require zendframework/zend-authentication

Concept

Usually, a developer writes a php function to authenticate the user details against a datasource. Once the authentication is done, the authentication details are persisted for subsequent requests. Zend Framework generalizes this concept and provides two classes, which are explained below −

Class 1 Zend\Authentication\Adaptor\AdaptorInterface

This class provides a single method, authenticate to write the authentication logic. The authenticate method returns an instance of Zend\Authentication\Result class.

This Result object holds the authentication status; identity if the authentication succeeds and an error message, if the authentication fails. The signature of the authenticate interface and result class is as follows −

AdaptorInterface

namespace Zend\Authentication\Adaptor; 
public function authenticate() { 
   // code 
}

Result class

namespace Zend\Authentication; 
class Result { 
   public function __construct($code, $identity, array $messages = []); 
}

The Zend Framework provides a default implementation to authenticate against the database, ldap, http basic and digest credentials. An Adaptor authenticates but does not persist the details for any future requests.

Class 2 Zend\Authentication\AuthenticationService

The AuthenticationService is the main component, which uses the already configured adaptor for authentication purposes. Once the authentication is done, it persists the authentication details and provides methods, hasIdentity() to check whether an identity is available, getIdentity() to get the authentication details and clearIdentity() to clear the authentication details.

The partial code listing to use this AuthenticationService is as follows −

$adap = new Adapter($username, $password);  
$auth = new AuthenticationService(); 
$result = $auth->authenticate($adap);  
if($result->isValid) { 
   $identity = $auth->getIdentity(); 
} else { 
   // process $result->getMessages() 
}  
// clear 
$auth->clearIdentity();

The stuff related to authorization are packaged as two separate modules, which are – zend-permissions-acl and zend-permissions-rbac. The zend-permissions-acl is based on the Access control list and the zend-permissions-rbac is based on the role based access control list. They provide high-level abstraction of ACL & RBAC concept and aids in writing the enterprise grade application.

Advertisements