HTTP Basic Authentication from Database for Slim

HTTP Basic Authentication middleware comes with simple PDO authenticator. It can be used to authenticate users from database. Authenticator assumes username and hashed password are stored in database. Default name for database table is users. Default column names for username and hash are unsurprisingly user and hash. Column and table names can also be set in options. Hash must be created with password_hash() function. Simplest possible table to store user data looks something like this.

CREATE TABLE users (
    user VARCHAR(32) NOT NULL,
    hash VARCHAR(255) NOT NULL
)

You can then insert an user with following.

$user = "root";
$hash = password_hash("t00r", PASSWORD_DEFAULT);

$status = $pdo->exec(
    "INSERT INTO users (user, hash) VALUES ('{$user}', '{$hash}')"
);

With some users in database you can use them in basic auth.

use \Slim\Middleware\HttpBasicAuthentication\PdoAuthenticator;

$pdo = new \PDO("sqlite:/tmp/users.sqlite");

$app = new \Slim\Slim();

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "authenticator" => new PdoAuthenticator([
        "pdo" => $pdo
    ])
]));

Different database naming

To override default table and column names you can pass them in options.

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "authenticator" => new PdoAuthenticator([
        "pdo" => $pdo,
        "table" => "accounts",
        "user" => "username",
        "hash" => "hashed"
    ])
]));

Install

You can install latest version using composer. Source is in GitHub.

$ composer require tuupola/slim-basic-auth

Posted in

PHP