In Defiance of Titles

Just another WordPress.com weblog

Archive for April 2009

Flexible User Authentication with Zend_Auth

with 3 comments

The Zend_Auth component of the Zend Framework can really help simplify the process of developing a custom authentication system for your next web application. The basic process is already very well-documented, so let’s try something a bit more complex.

For this example, we’re going to allow our users to authenticate in one of multiple ways: e.g., against a database table, against an LDAP server, or by OpenID [1]. Zend_Auth already provides the necessary authentication adapters, so what we’ll be concerned with here is how to implement all three systems without ending up in an FSUC situation.

As I see it, the controller layer ought to have very little awareness of the underlying authentication mechanisms. Here’s what such a controller might look like:

class AuthController extends Zend_Controller
{
  public function loginAction()
  {
    // one composite authentication adapter encapsulates
    // all the possible auth strategies, and provides appropriate
    // form instances for each
    $adapter = new My_Auth_Adapter_Multipath();
    $adapter->setStrategy($this->_getParam('via', null));
    $form = $adapter->getForm();
    $this->view->form = $form;

    // we'll also need an empty user object for this
    $user = new My_User(array());
    $adapter->setUser($user);

    // and then, if the user has submitted the form and it
    // passes simple validation, go ahead and try to authenticate
    if ($adapter->shouldAuthenticate($this->getRequest(), 
                                     $this->getResponse()) 
     && $form->isValid($this->_getAllParams())) {
      $user->populate($form->getValues());

      $auth = Zend_Auth::getInstance();
      $this->view->authResult = $auth->authenticate($adapter);
      $this->render('result');
    }
  }
}

Looks pretty clean to me. The view script is even cleaner:

<h1><?= $this->translate('Log in') ?></h1>
<?= $this->form ?>
<h2><?= $this->translate('Other ways to log in') ?></h2>
<ul>
  <li><a href="<?= $this->url(array('via' => 'email')) ?>"><?= $this->translate('Email') ?></a></li>
  <li><a href="<?= $this->url(array('via' => 'euid')) ?>"><?= $this->translate('EUID') ?></a></li>
  <li><a href="<?= $this->url(array('via' => 'openid')) ?>"><?= $this->translate('OpenID') ?></a></li>
</ul>

The real magic is all happening behind the scenes in the model layer. Let’s take a look at the authentication adapter next:

class My_Auth_Adapter_Multipath implements Zend_Auth_Adapter_Interface
{
  protected $_strategies;

  protected $_user;
  protected $_strategy;
  protected $_request;
  protected $_response;

  public function __construct()
  {
    $this->_strategies = new Zend_Loader_PluginLoader(array(
      'My_Auth_Strategy' => 'My/Auth/Strategy/',
    ));
  }

  public function shouldAuthenticate(Zend_Controller_Request_Http $request, 
                                     Zend_Controller_Response_Http $response)
  {
    if (null === $this->_strategy) {
      throw new Zend_Auth_Adapter_Exception('cannot determine; must set strategy first');
    }
    $this->setRequest($request);
    $this->setResponse($response);
    return $this->_strategy->shouldAuthenticate();
  }

  public function authenticate()
  {
    if (null === $this->_user || null === $this->_strategy) {
      throw new Zend_Auth_Adapter_Exception('must provide both user and strategy');
    }
    return $this->_strategy->authenticate();
  }

  public function getForm()
  {
    if (null === $this->_strategy) {
      throw new Zend_Auth_Adapter_Exception('must provide strategy first');
    }
    return $this->_strategy->getForm();
  }

  public function getUser()
  {
    return $this->_user;
  }

  public function setUser(My_User $user)
  {
    $this->_user = $user;
    return $this;
  }

  public function getStrategy()
  {
    return $this->_strategy;
  }

  public function setStrategy($strategy)
  {
    if (!($strategy instanceof My_Auth_Strategy_Interface)) {
      $strategyClass = $this->_strategies->load(ucfirst($strategy));
      $strategy = new $strategyClass();
      $strategy->setAdapter($this);
    }
    $this->_strategy = $strategy;
    return $this;
  }

  public function getRequest()
  {
    return $this->_request;
  }

  public function setRequest(Zend_Controller_Request_Http $request)
  {
    $this->_request = $request;
    return $this;
  }

  public function getResponse()
  {
    return $this->_response;
  }

  public function setResponse(Zend_Controller_Response_Http $response)
  {
    $this->_response = $response;
    return $this;
  }
}

A few things worth noting here. First…usually in this type of workflow the controller would check $this->getRequest()->isPost() prior to firing the authentication method; however, certain authentication strategies may require authentication to fire on other conditions (for instance, the OpenID adapter should fire when the openid_mode parameter is set, regardless of the request method). So, we leave it up to the adapter’s shouldAuthenticate() method to determine if the request warrants authentication.

Second, note that we still don’t have much in the manner of authentication code; that’s because, in order to keep things as flexible as possible, we’ve offloaded the actual authentication work to an arbitrary collection of strategy classes [2], provided dynamically through a Zend_Loader_PluginLoader instance (to make this worth it, we’ll also eventually want to add methods for registering new plugin paths, but I’ve left that out for the sake of brevity). Each strategy class will need to conform to the following interface:

interface My_Auth_Strategy_Interface extends Zend_Auth_Adapter_Interface
{
  public function setAdapter(My_Auth_Adapter_Multipath $adapter);
  public function getForm();
  public function shouldAuthenticate();
}

Internally, each authentication strategy will simply configure one of the core Zend_Auth adapters, run its authentication method, and, if successful, ensure that the identity returned in the Zend_Auth_Result instance is the completely-loaded user object. Let’s take a look at the simplest of the three examples, which checks the user’s email address and password against a backend database table:

class My_Auth_Strategy_Email implements My_Auth_Strategy_Interface
{
  protected $_adapter;

  public function setAdapter(My_Auth_Adapter_Multipath $adapter)
  {
    $this->_adapter = $adapter;
    return $this;
  }

  public function getForm()
  {
    $form = new Zend_Form();
    $form->addElement('text', 'email');
    $form->email->setLabel('Email address')
                ->setRequired(true)
                ->setFilters(array('StringTrim'))
                ->setValidators(array(
                  array('EmailAddress'),
                ));
    $form->addElement('password', 'pword');
    $form->pword->setLabel('Password')
                ->setRequired(true);
    $form->addElement('submit', 'submitBtn');
    $form->submitBtn->setLabel('Submit');
    return $form;
  }

  public function shouldAuthenticate()
  {
    return $this->_adapter->getRequest()->isPost();
  }

  public function authenticate()
  {
    $user = $this->_adapter->getUser();
    if (null === $user->email || null === $user->pword) {
      throw new Zend_Auth_Adapter_Exception('must provide email and password');
    }

    // use an internal Zend_Auth_Adapter_DbTable instance
    // to do the actual authentication
    $internalAdapter = new Zend_Auth_Adapter_DbTable(
      Zend_Registry::get('dbAdapter'),
      'users',
      'email',
      'pword'
    );
    $internalAdapter->setIdentity($user->email)
                    ->setCredential($user->pword);

    $result = $internalAdapter->authenticate();
    // per the stated requirements, we also want to make
    // sure that Zend_Auth stores a fully-completed user
    // object as the user's identity; so, we'll populate the
    // user object from the retrieved row and then set up
    // a new result object containing the correct identity
    if ($result->isValid()) {
      $user->populate($internalAdapter->getResultRowObject());
    }
    $result = new Zend_Auth_Result($result->getCode(), $user, $result->getMessages());
    return $result;
  }
}

We’ll use the same principle in designing the remaining two authentication methods (LDAP, which our users will know as their “EUID” or “Enterprise User ID”, and OpenID). I’ve left getForm() and setAdapter() out of these next examples, because the basic technique won’t be much different.

class My_Auth_Strategy_Euid implements My_Auth_Strategy_Interface
{
  // ...

  public function shouldAuthenticate()
  {
    return $this->_adapter->getRequest()->isPost();
  }

  public function authenticate()
  {
    $user = $this->_adapter->getUser();
    if (null === $user->euid || null === $user->euidPword) {
      throw new Zend_Auth_Adapter_Exception('must provide EUID and EUID password');
    }

    $ldapOptions = $this->_getLdapOptions();
    $internalAdapter = new Zend_Auth_Adapter_Ldap($ldapOptions, 
                                                  $user->euid, 
                                                  $user->euidPword);
    $result = $internalAdapter->authenticate();
    if ($result->isValid()) {
      // again, we'll need to populate the user object from the
      // database here, only this time we'll need to actually load
      // the user in manually since LDAP is a different system
      $table = new My_Db_Table_Users();
      $select = $table->select()->where('euid = ?', $user->euid);
      $userRow = $table->fetchRow($select);
      if (null === $userRow) {
        // the user has a valid LDAP account, but doesn't have an
        // account on our site yet, so we'll need to create one
        // programmatically...I won't demonstrate this here, though
      }
      $user->populate($userRow);
    }
    $result = new Zend_Auth_Result($result->getCode(), $user, $result->getMessages());
    return $result;
  }

  // ...
}

And finally, a strategy class for OpenID. Note that this is a bit more difficult owing to the necessity of client redirects; the OpenID strategy needs to be aware of quite a few more details, most of which are stored in the request object injected from the controller during the shouldAuthenticate() method.

class My_Auth_Strategy_Openid implements My_Auth_Strategy_Interface
{
  // ...

  public function shouldAuthenticate()
  {
    $request = $this->_adapter->getRequest();
    if ($request->isPost() 
     && $request->getParam('openid_action', null) == 'login' 
     && null !== $request->getParam('openid_identifier', null)) {
      return true;
    }
    if (null !== $request->getParam('openid_mode', null)) {
      return true;
    }
    return false;
  }

  public function authenticate()
  {
    $user = $this->_adapter->getUser();
    if (null === $user->openid_identifier) {
      throw new Zend_Auth_Adapter_Exception('must provide openid');
    }

    $storageDir = APPLICATION_PATH . '/../temp/openid_storage';
    $storage = new Zend_OpenId_Consumer_Storage_File($storageDir);

    $internalAdapter = new Zend_Auth_Adapter_OpenId(
      $user->openid_identifier,
      $storage,
      null,
      null,
      null,
      $this->_adapter->getResponse()
    );

    $result = $internalAdapter->authenticate();
    if ($result->isValid()) {
      // again, load the user from the database and populate
      // the user object; note that if the user doesn't yet have
      // an account on our site, the above code would be very
      // easy to modify such that it uses the OpenID simple
      // registration extension to create the user automatically
    }
    $result = new Zend_Auth_Result($result->getCode(), $user, $result->getMessages());
    return $result;
  }
}

The end result of all this is an extremely flexible (and extremely extensible) user authentication system with very little business logic in the controller.

Footnotes

  1. [Back] The idea is similar, but not identical, to the Zend_Auth_Adapter_Chain proposal from January 2008; the main difference here is that instead of authenticating against a series of several adapters, we’re simply going to have one main adapter that orchestrates the whole procedure via easily-selected strategies. Only one authentication technique will ultimately fire.
  2. [Back] If you look at the code later on, you’ll see that my authentication “strategy” interface is just an extension of Zend_Auth_Adapter_Interface allowing each implementation to provide a few extra standard features (forms, request analysis, etc.). I suppose it would have been reasonable to simply call them adapters, but I decided on using a new (still fairly standard) name to make it clear that they’re doing more than the standard Zend_Auth adapter would do. It was also necessary to namespace these classes separately from any other Zend_Auth adapters that might be included in a given application, so that the plugin loader never accidentally loads a different implementation of Zend_Auth_Adapter_Interface.

Written by jazzslider

April 9, 2009 at 6:52 am

Output Transformation in a Zend Framework Model Layer

with 4 comments

A few weeks back, Matthew Weier-O’Phinney wrote a very helpful discussion of model layer infrastructure using various components of the Zend Framework. I especially appreciated his advice on using Zend_Form as an input filter inside the model class itself; it provides a very clean way to keep validation and filtering logic properly encapsulated.

Zend_Form’s use of Zend_Filter and Zend_Validate also makes it very easy to get precisely the filtering and validation rules you need. You can even filter through an external library like HTMLPurifier if you find you need the extra functionality, just by writing a new filter class; this has already been covered quite well (for example, see Part 8, Step 3 of Pádraic Brady’s Zend Framework blog tutorial). As Weier-O’Phinney demonstrates, you can then use this Zend_Form object as a screening filter in your model class, so that certain properties must always pass through the form’s validation process before they are set in the model itself. I won’t duplicate his logic here either, but you should definitely take a look at it.

However, I’ve run into a minor problem, and I’m not sure my solution is particularly ideal. See, the Zend_Form approach described above does a great job of implementing Chris Shiflett’s Filter Input, Escape Output principle…user input is filtered for invalid HTML before it’s ever saved to the model, and can then be escaped as appropriate in the view layer. But what happens if you need to be able to retrieve the user’s original unfiltered input later?

That might not sound like an appropriate thing to do, but consider this. Suppose that instead of simply sanitizing user-contributed HTML, you wanted to allow your users to use a simpler text input format (such as Markdown) and generate the HTML for them later? It wouldn’t be appropriate to save the generated HTML to the model, since your users would then be unable to retrieve their original Markdown version for later editing. However, if you don’t pre-generate the HTML, then you can’t perform your HTMLPurifier sanitizing at the input stage either, since there isn’t any HTML to sanitize yet.

In this situation, it looks to me like you’d be stuck doing all your input filtering in the presentation (output) layer, which doesn’t really dovetail well with Shiflett’s principle. But then again, there do appear to be two distinct types of “filtering” at work here, one of which is what Shiflett was talking about, and the other of which probably isn’t:

  1. Sanitization, or making sure that user input doesn’t contain any security risks.
  2. Transformation, or converting user input for presentational purposes. (I feel like this is different from escaping, since escaping is mainly concerned with defusing special characters?)

So what do you think? It’s clear that sanitization ought to be done immediately upon input (preferably in the form object), but where should transformation happen?

Rob Allen’s Zend Framework Overview from last year hints at implementing things like Markdown formatting in the view layer through the use of view helpers. This is certainly appropriate from a strict MVC perspective, as output transformation is definitely presentation-layer stuff. However, this isn’t particularly DRY; every time you wrote a view script utilizing this data, you’d need to remember to run it through the appropriate chain of output filters.

So, my best overall idea (building on Weier-O’Phinney’s examples) is to implement it in the getters in my model:

class My_Model
{
  // ...
  public function __get($property)
  {
    $method = 'get' . ucwords($property);
    if (method_exists($this, $method)) {
      return $this->$method();
    }
    if (array_key_exists($property, $this->_data)) {
      return $this->_data[$property];
    }
    return null;
  }

  public function getBody($applyOutputFilter = true)
  {
    $body = $this->_data['body'];
    if ($applyOutputFilter) {
      $body = $this->getOutputFilter()->filter($body);
    }
    return $body;
  }

  public function getOutputFilter()
  {
    $filterChain = new Zend_Filter();
    // add specific filter objects as appropriate, and then...
    return $filterChain;
  }
  // ...
}

This guarantees that whenever the “body” is accessed as a property, it’s correctly transformed for HTML output (a sensible default).

However, both of these approaches still leave us with the same core problem: you almost inevitably end up doing all your input filtering at the presentation stage, rather than prior to saving it to the persistence layer as is usually recommended. This can be a security risk if you’re not careful, and is almost certainly a performance hit for the average visiting user.

Any ideas on how best to resolve these issues?

Written by jazzslider

April 6, 2009 at 7:11 am