Authentication with zend framework


Published on

Presentation is from

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Authentication with zend framework

  1. 1. Authentication with Zend Framework Darby Felton PHP Developer, Zend Technologies Zend Framework facilitates development of PHP applications requiring authentication by providing a simple, object-oriented API and adapters for popular authentication mechanisms.
  2. 2. Topics Overview <ul><li>Introduction to Zend Framework </li></ul><ul><li>Authentication with Zend_Auth </li></ul><ul><li>Zend_Auth_Adapter_OpenId </li></ul><ul><li>Integrating OpenID with Zend Framework MVC </li></ul><ul><li>Demonstration </li></ul><ul><li>Q & A </li></ul>
  3. 3. Introduction to Zend Framework <ul><li>What is Zend Framework? </li></ul><ul><li>The leading open-source PHP framework has a flexible architecture that lets you easily build modern web applications and web services. </li></ul><ul><li>Open Source </li></ul><ul><ul><li>New BSD license is business-friendly </li></ul></ul><ul><ul><li>Free for development and distribution </li></ul></ul><ul><ul><li>CLA process assures that the code is free of legal issues </li></ul></ul>
  4. 4. Introduction to Zend Framework <ul><li>Overview of Zend Framework goals: </li></ul><ul><li>Extreme simplicity </li></ul><ul><li>Use-at-will architecture </li></ul><ul><li>Designed for extensibility </li></ul><ul><li>Extensive documentation and testing </li></ul><ul><li>Continuous community involvement </li></ul>
  5. 5. Introduction to Zend Framework <ul><li>Zend Framework by the numbers: </li></ul><ul><li>Component Library – over 195,000 lines of PHP </li></ul><ul><li>Documentation – thorough reference guide with over 500 code examples and API docs available </li></ul><ul><li>Quality & Testing – over 4,400 unit tests run under the default test configuration </li></ul><ul><li>Community - over 390 contributors, over 100 SVN committers </li></ul><ul><li>Over 3.8 million downloads </li></ul><ul><li>Supports PHP 5.1.4 and later </li></ul>
  6. 6. Authentication with Zend_Auth <ul><li>First, let's define authentication for our purposes: </li></ul><ul><li>Authentication – determining whether an entity is actually what it purports to be, based on some set of credentials </li></ul><ul><li>We are interested in authenticating requesters of our web applications and services, and this is the primary purpose for which Zend_Auth was designed. </li></ul>
  7. 7. Authentication with Zend_Auth <ul><li>Benefits of Zend_Auth: </li></ul><ul><li>Designed to authenticate the requester's identity against some authentication mechanism (e.g., HTTP Basic/Digest, database table, LDAP) </li></ul><ul><li>Supports user-defined authentication adapters </li></ul><ul><li>Available automatic identity persistence </li></ul><ul><li>Configurable identity storage implementation </li></ul><ul><li>Provides simple authentication and storage interfaces, easily implemented by developers </li></ul>
  8. 8. Authentication with Zend_Auth <ul><li>Zend_Auth implements the Singleton pattern: </li></ul><ul><li>Exactly one instance of the Zend_Auth class is available at any time, using getInstance() : </li></ul><ul><li>Why implement the Singleton pattern? Exactly one request per PHP execution lifetime. </li></ul><ul><li>Operators new and clone are unavailable </li></ul>assert(Zend_Auth::getInstance() instanceof Zend_Auth);
  9. 9. Authentication with Zend_Auth <ul><li>Two ways to authenticate using a Zend_Auth adapter: </li></ul><ul><ul><li>Indirectly, through Zend_Auth::authenticate() </li></ul></ul><ul><ul><li>Directly, through the adapter’s authenticate() method </li></ul></ul><ul><li>By indirect usage the authenticated identity is automatically saved to persistent storage </li></ul><ul><li>Direct usage of Zend_Auth adapters enables developers to forgo automatic identity storage </li></ul>
  10. 10. Authentication with Zend_Auth <ul><li>What of this &quot;automatic identity persistence&quot;? </li></ul><ul><li>Successful authentication persists the identity across multiple requests (HTTP is stateless per se) </li></ul><ul><li>By default, Zend_Auth automatically persists a successfully authenticated identity to the PHP session using Zend_Auth_Storage_Session </li></ul><ul><li>Override this behavior by passing an object that implements Zend_Auth_Storage_Interface to Zend_Auth::setStorage() </li></ul><ul><li>If automatic identity storage is undesirable, developers may directly authenticate against a Zend_Auth adapter </li></ul>
  11. 11. Authentication with Zend_Auth <ul><li>Implementing Zend_Auth_Storage_Interface: </li></ul><ul><li>boolean isEmpty() </li></ul><ul><li>mixed read() </li></ul><ul><li>void write(mixed $contents) </li></ul><ul><li>void clear() </li></ul>
  12. 12. Authentication with Zend_Auth <ul><li>What constitutes a Zend_Auth adapter? </li></ul>class MyAuthAdapter implements Zend_Auth_Adapter_Interface { /** * Performs an authentication attempt     * @throws Zend_Auth_Adapter_Exception     * @return Zend_Auth_Result     */ public function authenticate()     {     } }
  13. 13. Authentication with Zend_Auth <ul><li>When does authenticate() throw an exception? </li></ul><ul><li>If and only if the authentication query cannot be answered </li></ul><ul><ul><li>Authentication service (e.g., DB, LDAP) is unavailable </li></ul></ul><ul><ul><li>Cannot open password file </li></ul></ul><ul><li>Not under normal authentication failure circumstances </li></ul><ul><ul><li>Username does not exist in the system </li></ul></ul><ul><ul><li>Password is incorrect </li></ul></ul>
  14. 14. Authentication with Zend_Auth <ul><li>Authentication results are returned as a Zend_Auth_Result object, which provides: </li></ul><ul><li>boolean isValid() </li></ul><ul><li>integer getCode() </li></ul><ul><li>mixed getIdentity() </li></ul><ul><li>array getMessages() </li></ul>
  15. 15. Authentication with Zend_Auth <ul><li>Using a Zend_Auth adapter indirectly: </li></ul><ul><li>Authenticated identity is saved automatically </li></ul>$authAdapter = new MyAuthAdapter($username, $password); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($authAdapter); if (!$result->isValid()) { switch ($result->getCode()) { ... }      foreach ($result->getMessages() as $message) {         echo &quot;$messagen&quot;;     } } else { echo 'Welcome, ' . $result->getIdentity() . &quot;n&quot;; }
  16. 16. Authentication with Zend_Auth <ul><li>Querying Zend_Auth about the authenticated identity: </li></ul><ul><li>boolean hasIdentity() </li></ul><ul><li>mixed|null getIdentity() </li></ul><ul><li>void clearIdentity() </li></ul>$auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { echo 'Hello, ' . $auth->getIdentity(); } else { echo 'Hello, anonymous'; } $auth->clearIdentity(); // &quot;log out&quot;
  17. 17. Authentication with Zend_Auth <ul><li>Bypass Zend_Auth, directly authenticating against an adapter: </li></ul><ul><li>No automatic storage of authenticated identity </li></ul>$authAdapter = new MyAuthAdapter($username, $password); $result = $authAdapter->authenticate(); if (!$result->isValid()) { switch ($result->getCode()) { ... }     foreach ($result->getMessages() as $message) {         echo &quot;$messagen&quot;;     } } else { echo 'Welcome, ' . $result->getIdentity() . &quot;n&quot;; }
  18. 18. Authentication with Zend_Auth <ul><li>Zend_Auth adapters currently available in Zend Framework (Zend_Auth_Adapter_ X ): </li></ul><ul><li>DbTable: accounts in a database table </li></ul><ul><li>Digest: file-based digest authentication </li></ul><ul><li>Http: supports HTTP Basic and Digest </li></ul><ul><li>InfoCard: works with Microsoft Information Card </li></ul><ul><li>Ldap: authenticate using LDAP services </li></ul><ul><li>OpenId : supports OpenID providers </li></ul>
  19. 19. Zend_Auth_Adapter_OpenId <ul><li>What is OpenID? From Wikipedia: </li></ul><ul><ul><li>OpenID is a decentralized single sign-on system. Using OpenID-enabled sites, web users do not need to remember traditional authentication tokens such as username and password. Instead, they only need to be previously registered on a website with an OpenID &quot;identity provider&quot; (IdP). Since OpenID is decentralized, any website can employ OpenID software as a way for users to sign in; OpenID solves the problem without relying on any centralized website to confirm digital identity. </li></ul></ul>
  20. 20. Zend_Auth_Adapter_OpenId <ul><li>How does OpenID work? </li></ul><ul><li>We won't discuss the details here... </li></ul>
  21. 21. Zend_Auth_Adapter_OpenId <ul><li>In order to use OpenID, you will need an OpenID provider. (You can also roll your own with ZF.) </li></ul><ul><li>Many providers exist, and you may already have an OpenID if you use AOL, LiveDoor, LiveJournal, Orange (France Telecom), SmugMug, Technorati, Vox, or WordPress. </li></ul><ul><li>You can also get an OpenID from ClaimID,, myOpenID, myVidoop, Verisign, and many others. </li></ul><ul><li>Learn more about OpenID at </li></ul>
  22. 22. Zend_Auth_Adapter_OpenId <ul><li>Generally, there is not much to using Zend_Auth_Adapter_OpenId, as it performs all the OpenID-specific heavy lifting for you. </li></ul><ul><li>Simply instantiate it, passing an OpenID to the constructor (or use setIdentity() ). </li></ul><ul><li>Zend_Auth_Adapter_OpenId is unique among the Zend_Auth adapters, however, in that its authenticate() method is called twice: </li></ul><ul><ul><li>Redirection to the OpenID provider </li></ul></ul><ul><ul><li>Handling response from OpenID provider </li></ul></ul>
  23. 23. Integrating OpenID with MVC <ul><li>Zend Framework provides implementations of the Front Controller and Model-View-Controller (MVC) patterns </li></ul><ul><li>Zend_Auth and its adapters do not require use of these patterns, but it is helpful to see how to integrate authentication with the Zend Framework MVC system </li></ul><ul><li>TIMTOWTDI, so we present an example </li></ul><ul><li>Here we use Zend_Auth_Adapter_OpenId </li></ul>
  24. 24. Integrating OpenID with MVC <ul><li>&quot;Bootstrapping&quot; Setup: </li></ul><ul><li>Web server routes to the bootstrap script </li></ul><ul><li>Application environment (error_reporting, include_path) </li></ul><ul><li>Autoloader </li></ul><ul><li>Load application configuration </li></ul><ul><li>Configure the Front Controller </li></ul><ul><li>Dispatch the Front Controller </li></ul><ul><li>Send the response to the client </li></ul>
  25. 25. Integrating OpenID with MVC <ul><li>Routing the web server to the bootstrap script </li></ul><ul><li>With Apache's mod_rewrite, we use .htaccess </li></ul><ul><li>To serve resources without ZF, modify the rule: </li></ul>RewriteEngine on RewriteRule ^.*$ index.php RewriteEngine on RewriteRule !.(js|ico|gif|jpg|png|css)$ index.php
  26. 26. Integrating OpenID with MVC <ul><li>What about this index.php ? </li></ul><ul><li>The only public-facing PHP file </li></ul><ul><li>Comprised of only two statements: </li></ul><ul><li>The class encapsulates the application logic </li></ul><?php require_once './application/library/My/App.php'; My_App::getInstance()->run();
  27. 27. Integrating OpenID with MVC <ul><li>Operations performed when running the application: </li></ul>public function run() { $this->_setupEnvironment() ->_setupAutoloader() ->_loadConfig() ->_setupFrontController() ->_dispatchFrontController(); return $this; }
  28. 28. Integrating OpenID with MVC <ul><li>Setting up the environment: error_reporting and include_path </li></ul>protected function _setupEnvironment() { error_reporting(E_ALL | E_STRICT); set_include_path($this->getPath('library') . PATH_SEPARATOR . get_include_path() ); return $this; }
  29. 29. Integrating OpenID with MVC <ul><li>Got autoloading? It's easy with Zend Framework: </li></ul>protected function _setupAutoloader() { require_once 'Zend/Loader.php'; Zend_Loader::registerAutoload(); return $this; }
  30. 30. Integrating OpenID with MVC <ul><li>Load the application configuration. Here, the configuration is minimal, including only baseUrl: </li></ul>protected function _loadConfig() { $this->_config = new Zend_Config_Ini( $this->getPath('application') . '/config.ini' ); return $this; }
  31. 31. Integrating OpenID with MVC <ul><li>Configure the Front Controller: </li></ul>protected function _setupFrontController() { Zend_Controller_Front::getInstance() ->throwExceptions(true) ->setBaseUrl($this->_config->baseUrl) ->setControllerDirectory( $this->getPath('application') . '/controllers') ->registerPlugin( new My_Controller_Plugin_Dispatch_Check()) ->registerPlugin( new My_Controller_Plugin_View_Layout()) ->returnResponse(true); return $this; }
  32. 32. Integrating OpenID with MVC <ul><li>Dispatch the Front Controller and send the response to the client: </li></ul>protected function _dispatchFrontController() { try { Zend_Controller_Front::getInstance() ->dispatch() ->sendResponse(); } catch (Exception $e) { echo $e->getMessage(); } return $this; }
  33. 33. Integrating OpenID with MVC <ul><li>All the Action Controllers, which handle application requests, extend a common controller class: </li></ul><ul><li>My_Controller_Action makes available certain information to the view layer: </li></ul><ul><ul><li>Whether the requester is authenticated </li></ul></ul><ul><ul><li>A user object that represents the requester </li></ul></ul><ul><ul><li>The baseUrl of the application (e.g., for links) </li></ul></ul>class IndexController extends My_Controller_Action
  34. 34. Integrating OpenID with MVC <ul><li>My_Controller_Action::preDispatch() : </li></ul>public function preDispatch() { $view = Zend_Controller_Action_HelperBroker::getStaticHelper( 'viewRenderer')->view; $auth = Zend_Auth::getInstance(); $view->authenticated = $auth->hasIdentity(); $view->user = new My_Model_User( $auth->getIdentity()); $view->baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl(); }
  35. 35. Integrating OpenID with MVC <ul><li>The interesting parts of LoginController::processAction() : </li></ul>$authAdapter = new Zend_Auth_Adapter_OpenId($openId); $authAdapterStorage = new Zend_OpenId_Consumer_Storage_File( My_App::getInstance()->getPath('data') ); $authAdapter->setStorage($authAdapterStorage); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($authAdapter);
  36. 36. Demonstration <ul><li>This webinar is accompanied by a demonstration of sample code highlighted in previous slides. The code can serve as a starting point for you to explore authentication with Zend Framework. </li></ul><ul><li>The webinar slides and sample application code will be made available soon after this presentation. </li></ul>
  37. 37. Q & A <ul><li>Stump the chump!  </li></ul>
  38. 38. Thank you! [email_address] [email_address]