As astute observers will have realized, the most-recent release of Solar had a new authentication adapter in it: Solar_Auth_Adapter_Typekey.

This particular class comes from work I'm doing at my current employer, Mashery. The Mashery folks are very open-source friendly, and approve of contributing back to useful projects, so I want to go out of my way and thank Mashery explicitly for this. (Thanks Mashery!)

Likewise, the core code in Solar_Auth_Adapter_Typekey comes directly from the PEAR Auth_TypeKey work by Daiji Hirata (which strangely has not been accepted yet at PEAR; their loss is Solar's gain). Thanks, Daiji, for contributing this code to Solar!

In this article, I'm going to talk a bit about Solar authentication in general, and then TypeKey authentication in specific.

Solar Authentication

Solar uses a facade class for authenticating users, Solar_Auth. That class acts as an interface to one of many underlying adapter classes that point to a backend storage service, such as an Apache htpasswd file, an SQL database table, an LDAP server, and so on. Anyone familiar with PEAR Auth will be familiar with this style of operation.

Let's instantiate an authentication object that uses the "htaccess" adapter, and start an authenticated session:

<?php
    $config = array(
        'adapter' => 'Solar_Auth_Adapter_Htaccess',
        'config' => array(
            'file' => '/path/to/htaccess.file',
        ),
    );

    $auth = Solar::factory('Solar_Auth', $config);

    $auth->start();
?>

Note: if you use the Solar.config.php file to set defaults for the Solar_Auth and Solar_Auth_Adapter_Htaccess classes, you can skip setting $config altogether and just call Solar::factory('Solar_Auth').

The start() call does a lot of work for you. By default, it checks $_POST for a series of variables indicating a login or logout attempt (and processes them according to the backend adapter). It also updates the idle and expire times of any currently authenticated user.

Note: the authentication process is highly configurable; at construction time, you can specify to use $_GET or $_POST, what variable indicates a login or logout attempt, the variable names for handle and passwd, the idle and expire times, and much more. See the page on config keys here.

You can check current authentication information this way:

<?php
    $auth = Solar::factory('Solar_Auth');
    $auth->start();

    // is the current user authenticated?
    $auth->isValid();

    // what is the current status code?
    //
    // 'ANON'    : The user has not attempted to authenticate
    // 'WRONG'   : The user attempted authentication but failed
    // 'VALID'   : The user is authenticated and has not timed out
    // 'IDLED'   : The authenticated user has been idle for too long
    // 'EXPIRED' : The max time for authentication has expired
    //
    $auth->status;

    // what's the current username?
    $auth->handle;

    // some adapters report the user's email address,
    // display name ("moniker"), and/or website URI.
    $auth->email;
    $auth->moniker;
    $auth->uri;

    // when did the user initally sign in, and when was the
    // last activity in this session?  reported as a unix
    // timestamp.
    $auth->initial;
    $auth->active;
?>

Of course, the user has to type this information into a form somewhere on your website. Here's a very simple example form:

<form action="index.php" method="post">
    <p>Username: <input type="text" name="handle" /></p>
    <p>Password: <input type="password" name="passwd" /></p>
    <p><input type="submit" name="submit" value="Sign In"/></p>

</form>

You can see a more complex authentication form that shows current status, handle, etc. here.

About TypeKey Authentication

TypeKey is an authentication service provided by the folks at Six Apart. The idea is that instead of signing up for a user account at every website you want to authenticate to, you can sign up for one account at TypeKey. Then other sites can check if you have been authenticated to a TypeKey account. This has a lot of obvious benefits for users (like having to remember only one password) and site owners (not having to maintain accounts).

The problem with TypeKey authentication is that, as far as site owners is concerned, it's vastly different from "standard" handle + passwd authentication. Instead of the user typing their username and password credentials into your site, you just show a link to the TypeKey website. The user presents his credentials to TypeKey, not to your site; TypeKey then redirects to your site again and sends a pack of information for you to verify.

You can read more about the authentication process at the TypeKey API page; you will see that it's a lot more complicated that just checking a username and password against a data store. This leads to an interesting problem for adapter-based authentication systems; it means that you have to abstract two different styles of authentication algorithms, not just one. Lucky for us, the Solar_Auth system is abstracted well enough to handle this. :-)

Pre-Requisities

First, because of the DSA encryption algorithm used in processing TypeKey authentication signatures, PHP has to have been compiled with either bcmath (--enable-bcmath) or the GMP extension (--with-gmp). These extensions provide the large-integer math functions necessary for decryption processing.

Next, you need a TypeKey account and the related "token" from that account to identify your website (the one where users will return to after authenticating with TypeKey).

And of course, you need the latest release of Solar.

TypeKey Login Link

Instead of a "normal" login form with username and password fields, you need to present a link to TypeKey for your users to click on. The link must include your TypeKey token and the URI of the page you want to return to as GET vars. Here's a detailed code example to show you what goes into building the link:

<?php
    $token = "your_typekey_token";

    $href = "https://www.typekey.com:443/t/typekey/login"
          . "?t=" . urlencode($token)
          . "&return=" . urlencode($_SERVER['REQUEST_URI']);

    echo '<a href="' . $href . '">Sign In</a>';
?>

TypeKey Adapter Setup

Now we need to tell Solar_Auth to expect TypeKey logins; we do this using the TypeKey adpater class. Then simply call the start() method.

<?php
    $config = array(
        'adapter' => 'Solar_Auth_Adapter_Typekey',
        'config'  => array(
            'token' => 'your_typekey_token',
        ),
    );

    $auth = Solar::factory('Solar_Auth', $config);

    $auth->start();
?>

That's all there is to it! Using the TypeKey adapter, Solar_Auth will recognize all TypeKey login attempts and track idle/expire times just as with other authentication sources. The adapter does all the work for you.

Again, my thanks to Daiji Hirata for his work on the core code for this adapter, and to Mashery for allowing me to include it as part of Solar.

Are you stuck with a legacy PHP application? You should buy my book because it gives you a step-by-step guide to improving you codebase, all while keeping it running the whole time.