HTTP Basic Authentication From Database for Slim

Blog Projects
PHP

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 table is users. Default column names for username and has are 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 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


When asking a question include an URL to example page where the problem occurs. Even better is to make a Fiddle which demonstrates the problem. If you have longer code examples please use pastie.org.