Authentication with zend framework

  • 3,909 views
Uploaded on

Presentation is from http://framework.zend.com/wiki/display/ZFUSER/Authentication+with+Zend+Framework

Presentation is from http://framework.zend.com/wiki/display/ZFUSER/Authentication+with+Zend+Framework

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,909
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
85
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

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