Search code examples
phpzend-frameworkauthenticationzend-framework-mvc

Zend_Auth best practices


My goal is to require login for certain pages. I am using Zend Framework MVC, and I'm trying to find examples regarding best practices.

Some notes on what I'm looking for:

  • I want non-logged in users to get a login box, and then return to logged in version of the page, once authenticated
  • I want to use dependency injection, and avoid singletons
  • Small code footprint - tie into Zend mvc structure
  • Should login box be a separate controller and do header redirect? How to return to landing page after auth success? An idea to simply call the login controller action to display the login box in the landing page, or is this a disadvantage regarding search engine indexing?
  • Be able to use external library for handling cookies

Or something completely different. I'm fairly new to the Zend framework, and I want to do it 'the right way'.


Solution

    • I want non-logged in users to get a login box, and then return to logged in version of the page, once authenticated

    Use a FrontController plugin and redirect or forward them to your loginAction.

    • I want to use dependency injection, and avoid singletons

    Zend Framework, doesn't currently ship any DI system, however, the Zend_Application_Resource_* actually replace it. What kind of dependency would you need here?

    • Small code footprint - tie into Zend mvc structure

    That's up to you.

    • Should login box be a separate controller and do header redirect? How to return to landing page after auth success? An idea to simply call the login controller action to display the login box in the landing page, or is this a disadvantage regarding search engine indexing?

    I mostly use a special AuthController with LoginAction & LogoutAction. To redirect the user to the page is was trying to view, I always add a returnUrl element in my forms, and I inject the value of the requested URL to be able to redirect the user, and if none, I redirect him to the index/dashboard, depends.

    • Be able to use external library for handling cookies

    Zend_Auth allows you to set your own storage mechanism, so just implement the interface.

    $auth = Zend_Auth::getInstance();
    $auth->setStorage(new My_Auth_Storage());
    

    But never store authentication result in a cookie, it's so easy to modify it and access your website.

    You may also take a look to one of my previous answer.