SlideShare a Scribd company logo
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.
Topics Overview Introduction to Zend Framework Authentication with Zend_Auth Zend_Auth_Adapter_OpenId Integrating OpenID with Zend Framework MVC Demonstration Q & A
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
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
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
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.
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
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);
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
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
Authentication with Zend_Auth Implementing Zend_Auth_Storage_Interface: boolean isEmpty() mixed read() void write(mixed $contents) void clear()
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()     {     } }
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
Authentication with Zend_Auth Authentication results are returned as a  Zend_Auth_Result  object, which provides: boolean isValid() integer getCode() mixed getIdentity() array getMessages()
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 "$message\n";     } } else { echo 'Welcome, ' . $result->getIdentity() . "\n"; }
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"
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 "$message\n";     } }   else { echo 'Welcome, ' . $result->getIdentity() . "\n"; }
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
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.
Zend_Auth_Adapter_OpenId How does OpenID work? We won't discuss the details here...
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
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
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
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
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
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();
Integrating OpenID with MVC Operations performed when running the application: public function run() { $this->_setupEnvironment() ->_setupAutoloader() ->_loadConfig() ->_setupFrontController() ->_dispatchFrontController(); return $this; }
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; }
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; }
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; }
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; }
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; }
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
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(); }
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);
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.
Q & A Stump the chump!  
Thank you! http://framework.zend.com [email_address] [email_address]

More Related Content

ODP
Implementing security routines with zf2
PDF
Instant ACLs with Zend Framework 2
PDF
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
ODP
TangoWithDjango - ch8
PDF
Deprecated: Foundations of Zend Framework 2
PDF
Real World Dependency Injection - IPC11 Spring Edition
PDF
Real World Dependency Injection - phpugffm13
PDF
Dependency Injection in PHP - dwx13
Implementing security routines with zf2
Instant ACLs with Zend Framework 2
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
TangoWithDjango - ch8
Deprecated: Foundations of Zend Framework 2
Real World Dependency Injection - IPC11 Spring Edition
Real World Dependency Injection - phpugffm13
Dependency Injection in PHP - dwx13

What's hot (19)

PDF
Skyrocketing Web APIs
PDF
A quick start on Zend Framework 2
PPT
Security in java ee platform: what is included, what is missing
PDF
Quick start on Zend Framework 2
PPTX
Intro to Pentesting Jenkins
PDF
Real World Dependency Injection - PFCongres 2010
PDF
Testing untestable code - oscon 2012
PPT
JavaEE Security
PDF
Zend Framework 2 - Basic Components
PPTX
Pentesting Modern Web Apps: A Primer
PDF
Real World Dependency Injection SE - phpugrhh
PDF
Web application security (eng)
ODP
Introduction to Zend Framework
PDF
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
PDF
Hacking the Grails Spring Security Plugins
PDF
Portlet Specification 3.0 Is Here!
PDF
Java Web Programming [9/9] : Web Application Security
PPT
Developing With JAAS
PDF
How to Implement Token Authentication Using the Django REST Framework
Skyrocketing Web APIs
A quick start on Zend Framework 2
Security in java ee platform: what is included, what is missing
Quick start on Zend Framework 2
Intro to Pentesting Jenkins
Real World Dependency Injection - PFCongres 2010
Testing untestable code - oscon 2012
JavaEE Security
Zend Framework 2 - Basic Components
Pentesting Modern Web Apps: A Primer
Real World Dependency Injection SE - phpugrhh
Web application security (eng)
Introduction to Zend Framework
PHPSpec & Behat: Two Testing Tools That Write Code For You (#phptek edition)
Hacking the Grails Spring Security Plugins
Portlet Specification 3.0 Is Here!
Java Web Programming [9/9] : Web Application Security
Developing With JAAS
How to Implement Token Authentication Using the Django REST Framework
Ad

Similar to Authentication with zend framework (20)

PPS
Implementing access control with zend framework
PPT
PPTX
My first zf presentation part two
KEY
PPTX
Zend server 6 compliance
PDF
Php web app security (eng)
PDF
Distributed Identity via OpenID
PPTX
Zend MVC pattern based Framework – Best for Enterprise web applications
DOCX
Zend framework 2.0
KEY
OpenID - An in depth look at what it is, and how you can use it
PDF
Yii Framework Security
KEY
IoC with PHP
ODP
Creating Web Services with Zend Framework - Matthew Turland
PPT
San Francisco PHP Meetup Presentation on Zend Framework
PDF
Digital Identity
PPTX
Creating a Sign On with Open id connect
PPT
Open Id, O Auth And Webservices
PPT
Implementing OpenID for Your Social Networking Site
PDF
Introduction Yii Framework
PPT
Download It
Implementing access control with zend framework
My first zf presentation part two
Zend server 6 compliance
Php web app security (eng)
Distributed Identity via OpenID
Zend MVC pattern based Framework – Best for Enterprise web applications
Zend framework 2.0
OpenID - An in depth look at what it is, and how you can use it
Yii Framework Security
IoC with PHP
Creating Web Services with Zend Framework - Matthew Turland
San Francisco PHP Meetup Presentation on Zend Framework
Digital Identity
Creating a Sign On with Open id connect
Open Id, O Auth And Webservices
Implementing OpenID for Your Social Networking Site
Introduction Yii Framework
Download It
Ad

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Approach and Philosophy of On baking technology
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Reach Out and Touch Someone: Haptics and Empathic Computing
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25-Week II
Network Security Unit 5.pdf for BCA BBA.
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Assigned Numbers - 2025 - Bluetooth® Document
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Approach and Philosophy of On baking technology
Programs and apps: productivity, graphics, security and other tools
Review of recent advances in non-invasive hemoglobin estimation
MYSQL Presentation for SQL database connectivity
Digital-Transformation-Roadmap-for-Companies.pptx

Authentication with zend framework

  • 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 &quot;automatic identity persistence&quot;? 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 &quot;$message\n&quot;;     } } else { echo 'Welcome, ' . $result->getIdentity() . &quot;\n&quot;; }
  • 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(); // &quot;log out&quot;
  • 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 &quot;$message\n&quot;;     } } else { echo 'Welcome, ' . $result->getIdentity() . &quot;\n&quot;; }
  • 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 &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.
  • 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 &quot;Bootstrapping&quot; 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! 