HTTP Basic Auth in Silex

Silex is a great platform for building small web applications and APIs, recently I’ve been using it to build an API with only a couple of routes. As this API will only be used by a couple of users it made sense to use use HTTP basic auth (over SSL of course). HTTP auth could be left to apache/nginx etc. but that wouldn’t give me the control I’d like over the output and authentication so I implemented it in Silex, I hope someone finds this useful:

HTTP basic authentication is very simple and just passes a username and password in the headers, PHP has built in functionality to extract these values which can be used in the Silex before hook to ensure it happens before every request is fulfilled, my example is for an API which returns JSON but it would work equally well for a conventional website:

$app->before(function() use ($app)
{
    if (!isset($_SERVER['PHP_AUTH_USER']))
    {
        header('WWW-Authenticate: Basic realm='<website name>'');
        return $app->json(array('Message' => 'Not Authorised'), 401);
    }
    else
    {
        //once the user has provided some details, check them

        $users = array(
            'workflow' => 'password'
            );

        if($users[$_SERVER['PHP_AUTH_USER']] !== $_SERVER['PHP_AUTH_PW'])
        {
            //If the password for this user is not correct then resond as such

            return $app->json(array('Message' => 'Forbidden'), 403);
        }

        //If everything is fine then the application will carry on as normal

    }
});

Full details of implementing HTTP auth in PHP can be found in the PHP manual, this includes how to implement HTTP digest auth.