Documentation menu

Security

Authentication

This page covers who the user is: the Auth facade and its drivers, passwords, logging in with a session, protecting pages and API routes, remember-me cookies, JSON Web Tokens, policies, password reset and email verification tokens, and two-factor codes. The protections around them (CSRF, cookies, headers, encryption) are in Security.

Every PHP example below marked as runnable runs as written, in order, against SQLite.

Contents

#

The Auth facade

#

Taphra\Auth is a static facade over one driver. The default driver, Taphra\Auth\SessionAuth, keeps the user in the session and needs no setup. Taphra\Auth\JwtAuth reads a bearer token instead (see JSON Web Tokens).

Method Does
Auth::login(array $user) stores the user (an array with at least id); SessionAuth gives the session a new ID
Auth::logout() forgets the user; SessionAuth gives the session a new ID, JwtAuth revokes the token
Auth::check(): bool, Auth::guest(): bool whether a user is logged in
Auth::user(?string $field = null) the stored array, one field of it, or null
Auth::id() Auth::user('id')
Auth::require(): array the user, or a Taphra\Exceptions\UnauthorizedException (401)

To configure the driver, set it once in app/bootstrap.php:

PHP
// app/bootstrap.php
use Taphra\Auth;
use Taphra\Auth\SessionAuth;

Auth::setDriver(new SessionAuth([
    'session_key'     => '_tphr_user',      // where the user array lives in $_SESSION (default)
    'remember_cookie' => '_tphr_remember',  // remember-me cookie name (default)
    'secure'          => true,              // remember-me cookie over HTTPS only; default: detect HTTPS
]));

Store only what you need on every request in the user array (id, name, role), not the password hash.

Users and passwords

#

The examples use this table and DataStore:

PHP
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

$schema = new SchemaBuilder(DatabaseConnection::load('app_master'));
foreach (['remember_tokens', 'posts', 'users'] as $table) {
    $schema->dropIfExists($table);
}
$schema->create('users', function ($t) {
    $t->id();
    $t->string('name', 100);
    $t->string('email')->unique();
    $t->string('password');
    $t->string('role', 20)->default('author');
});
PHP
// app/DataStores/UserDataStore.php
namespace App\DataStores;

class UserDataStore extends AppDataStore
{
    public $objectName = 'users';
    protected $fillable = ['name', 'email', 'password', 'role'];
}

Auth::hashPassword() hashes with Argon2id when PHP supports it, otherwise bcrypt (password_hash()); it refuses a password containing a NUL byte, and with bcrypt one longer than 72 bytes (bcrypt ignores the rest), with an Auth\UnusablePasswordException whose message can be shown to the user. Auth::setPasswordAlgorithm() picks one explicitly. Auth::verifyPassword() checks a password against a hash in constant time; Auth::needsRehash() says when a stored hash should be replaced, for example after the cost or the algorithm changed: an existing bcrypt hash reports true once Argon2id is the default, so rehash it after a successful login.

PHP
use App\DataStores\UserDataStore;
use Taphra\Auth;

$alice = UserDataStore::create([
    'name'     => 'Alice',
    'email'    => '[email protected]',
    'password' => Auth::hashPassword('correct horse battery staple'),
    'role'     => 'admin',
]);

var_dump(Auth::verifyPassword('correct horse battery staple', $alice['password']));  // bool(true)
var_dump(Auth::verifyPassword('wrong', $alice['password']));                         // bool(false)
var_dump(Auth::needsRehash($alice['password']));                                     // bool(false)

Logging in with a session

#

A login page is a form and an action that checks the password, counts failed attempts, and calls Auth::login(). The skeleton's AppController checks the CSRF token of every POST, so the form carries it.

app/Config/routes.yml
GET:
  /login:    login/show
  /account:  account/index
POST:
  /login:    login/submit
  /logout:   login/logout
PUT:
  /posts/{id:\d+}: postEdit/update
groups:
  api:
    prefix: /api
    middleware: [Taphra\Http\AuthMiddleware]
    routes:
      GET /me: me/show
  jwt:
    prefix: /jwt
    middleware: [App\Http\ApiJwtMiddleware]
    routes:
      GET /me: jwtMe/show
app/Views/login/show.tpl.php
<?php // app/Views/login/show.tpl.php ?>
<h1>Sign in</h1>
<?php if ($error !== ''): ?>
  <p class="error"><?= e($error) ?></p>
<?php endif; ?>
<form method="post" action="/login">
  <?= $this->csrf() ?>
  <label>Email <input type="email" name="email" value="<?= e($email) ?>" required></label>
  <label>Password <input type="password" name="password" required></label>
  <button>Sign in</button>
</form>
PHP
// app/Controllers/LoginController.php
namespace App\Controllers;

use App\DataStores\UserDataStore;
use Taphra\Auth;
use Taphra\RateLimiter;
use Taphra\Request;

class LoginController extends AppController
{
    public function show(): void
    {
        $this->form('', '');
    }

    public function submit(): void
    {
        $email   = Request::str('email');
        $limiter = RateLimiter::make('login', 5, 900);       // 5 attempts per 15 minutes
        $key     = Request::clientIP() . '|' . strtolower($email);

        // attempt() counts and checks in one step: parallel requests cannot
        // all pass the check before one of them is counted.
        if (!$limiter->attempt($key)) {
            http_response_code(429);
            $this->form($email, 'Too many attempts. Try again in ' . $limiter->availableIn($key) . ' seconds.');
            return;
        }

        // An unknown email is checked against a dummy hash (null), so the
        // answer takes as long as for a real account.
        $user = UserDataStore::firstWhere(['email' => $email]);
        $password = (string) Request::input('password', '');  // not trimmed
        if (!Auth::verifyPassword($password, $user['password'] ?? null) || $user === null) {
            http_response_code(422);
            $this->form($email, 'These credentials do not match our records.');
            return;
        }

        $limiter->clear($key);
        Auth::login($user->only(['id', 'name', 'email', 'role']));
        $this->redirect('/account');
    }

    public function logout(): void
    {
        Auth::logout();
        $this->redirect('/login');
    }

    private function form(string $email, string $error): void
    {
        $this->viewTitle = 'Sign in';
        $this->email = $email;
        $this->error = $error;
        $this->render('show');
    }
}

redirect() sends the Location header and ends the request. The form, a failed attempt, and a post without the token:

PHP
use Taphra\Security;

$page = docs_request('GET', '/login');
echo $page->getStatusCode(), ' ', str_contains((string) $page->getBody(), 'name="_csrf_token"') ? 'has a token' : 'no token', "\n";
// 200 has a token

$token = Security::generateCsrfToken();   // the value the form carries
$failed = docs_request('POST', '/login', ['email' => '[email protected]', 'password' => 'wrong', '_csrf_token' => $token]);
echo $failed->getStatusCode(), "\n";      // 422

echo docs_request('POST', '/login', ['email' => '[email protected]', 'password' => 'wrong'])->getStatusCode(), "\n";
// 403 (no CSRF token)

On success the user array is in the session until logout:

PHP
use App\DataStores\UserDataStore;
use Taphra\Auth;

Auth::login(UserDataStore::firstWhere(['email' => '[email protected]'])->only(['id', 'name', 'email', 'role']));

var_dump(Auth::check());        // bool(true)
echo Auth::user('name'), "\n";  // Alice
echo Auth::id(), "\n";          // 1

Count failed attempts per account and address, as above, so a password cannot be guessed at speed; RateLimiter counts in a fixed window (see Security).

Protecting pages and API routes

#

For pages, check in beforeAction() and send guests to the login form:

PHP
// app/Controllers/AccountController.php
namespace App\Controllers;

use Taphra\Auth;

class AccountController extends AppController
{
    public function beforeAction()
    {
        parent::beforeAction();          // keeps the CSRF check
        if (Auth::guest()) {
            $this->redirect('/login');
        }
    }

    public function index(): string
    {
        return 'Hello, ' . e(Auth::user('name'));
    }
}

For APIs, put the routes in a group with Taphra\Http\AuthMiddleware (the api group in the routes file above). It answers a request without a logged-in user with 401 and a JSON body, and lets the others through. Route group middleware runs on both entries: the web front controller and the PSR-15 pipeline used by tests.

PHP
// app/Controllers/MeController.php
namespace App\Controllers;

use Taphra\Auth;
use Taphra\RestController;

class MeController extends RestController
{
    public function show(): string
    {
        return $this->json(Auth::require());
    }
}
PHP
use Taphra\Auth;

echo docs_request('GET', '/api/me')->getBody(), "\n";
// {"id":1,"name":"Alice","email":"[email protected]","role":"admin"}

Auth::logout();
$guest = docs_request('GET', '/api/me');
echo $guest->getStatusCode(), ' ', $guest->getHeaderLine('WWW-Authenticate'), "\n";
// 401 Bearer realm="Taphra"
echo $guest->getBody(), "\n";
// {"error":"Unauthorized","message":"Authentication required."}

new AuthMiddleware(['/api/health']) leaves the listed paths, and everything below them, open. A route bound to middleware is not reachable through its /controller/action convention URL either (that answers 404), so the middleware cannot be skipped.

Outside a group, Auth::require() in an action does the same check: it throws UnauthorizedException, which the framework answers with 401.

Remember me

#

Auth::loginWithRemember($user, int $days = 30, ?callable $store = null) logs in and sets a long-lived _tphr_remember cookie (HttpOnly, SameSite=Lax) holding a random token. Store a hash of the token, never the token. On a later visit without a session, Auth::resumeFromRemember(callable $userResolver, ?callable $rotateStore = null, int $days = 30) looks the token up and logs the user in; with $rotateStore it replaces the token on every resume, which limits how long a stolen cookie works. Auth::forgetRemember() deletes the cookie.

PHP
use App\DataStores\UserDataStore;
use Taphra\Auth;
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

(new SchemaBuilder(DatabaseConnection::load('app_master')))->create('remember_tokens', function ($t) {
    $t->id();
    $t->integer('user_id');
    $t->string('token_hash', 64)->unique();
    $t->dateTime('expires_at');
});
$tokens = DatabaseConnection::load('app_master');

// At login, when "remember me" is ticked:
$user  = UserDataStore::firstWhere(['email' => '[email protected]'])->only(['id', 'name', 'email', 'role']);
$token = Auth::loginWithRemember($user, 30, function (string $token, array $user) use ($tokens) {
    $tokens->execute(
        'INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?, ?, ?)',
        [$user['id'], hash('sha256', $token), date('Y-m-d H:i:s', time() + 86400 * 30)]
    );
});

// A later request: no session, only the cookie.
Auth::logout();
$_COOKIE['_tphr_remember'] = $token;

$resumed = Auth::resumeFromRemember(
    function (string $token) use ($tokens): ?array {
        $row = $tokens->query('SELECT user_id FROM remember_tokens WHERE token_hash = ? AND expires_at > ?',
            false, false, [hash('sha256', $token), date('Y-m-d H:i:s')]);
        return $row ? UserDataStore::findById($row['user_id'])?->only(['id', 'name', 'email', 'role']) : null;
    },
    function (string $new, string $old, array $user) use ($tokens) {
        $tokens->execute('UPDATE remember_tokens SET token_hash = ? WHERE token_hash = ?',
            [hash('sha256', $new), hash('sha256', $old)]);
    }
);
var_dump($resumed, Auth::user('name'));   // bool(true) string(5) "Alice"

Call resumeFromRemember() early in each request, for example at the top of AppController::beforeAction(). At logout call Auth::forgetRemember() with Auth::logout() and delete the stored hash. The cookie is Secure when the request itself is HTTPS ($_SERVER['HTTPS']); behind a proxy that ends TLS, pass 'secure' => true to SessionAuth.

JSON Web Tokens

#

There are two ways to authenticate API requests with a bearer token.

Jwt and JwtMiddleware (no extra package)

#

Taphra\Auth\Jwt signs and checks HS256 tokens with PHP's own functions. The secret must be at least 32 bytes; a shorter one throws InvalidArgumentException, on encode and decode alike. Generate one with php -r 'echo bin2hex(random_bytes(32)), "\n";' and keep it in the environment.

PHP
use Taphra\Auth\Jwt;

$secret = bin2hex(random_bytes(32));    // in an app: getenv('JWT_SECRET')
putenv("JWT_SECRET=$secret");

$jwt = Jwt::encode(['sub' => 1, 'role' => 'admin'], $secret, 900);  // iat and exp added; ttl 0 = no exp
$claims = Jwt::decode($jwt, $secret);   // RuntimeException: bad signature or expired; InvalidArgumentException: malformed
echo $claims['sub'], ' ', $claims['exp'] - $claims['iat'], "\n";     // 1 900

try {
    Jwt::encode(['sub' => 1], 'too-short');
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), "\n";        // JWT secret must be at least 32 bytes long; got 9.
}

Taphra\Auth\JwtMiddleware(string $secret, array $exclude = [], string $attribute = 'jwt_payload') checks the Authorization: Bearer header of every request it sees. A missing, malformed, badly signed or expired token gets 401 with an RFC 7807 body; a valid one continues with the claims in JwtMiddleware::payload() (null when no token was verified) and in the PSR-7 request attribute. Never read $_REQUEST['_jwt'] for this: a client can send that parameter on a route without the middleware. Route groups create their middleware without arguments, so give the secret in a small subclass:

PHP
// app/Http/ApiJwtMiddleware.php
namespace App\Http;

use Taphra\Auth\JwtMiddleware;

class ApiJwtMiddleware extends JwtMiddleware
{
    public function __construct()
    {
        parent::__construct((string) getenv('JWT_SECRET'));
    }
}
PHP
// app/Controllers/JwtMeController.php
namespace App\Controllers;

use Taphra\Auth\JwtMiddleware;
use Taphra\RestController;

class JwtMeController extends RestController
{
    public function show(): string
    {
        return $this->json(['user_id' => JwtMiddleware::payload()['sub'] ?? null]);
    }
}
PHP
echo docs_request('GET', '/jwt/me', [], ['Authorization' => "Bearer $jwt"])->getBody(), "\n";
// {"user_id":1}

$denied = docs_request('GET', '/jwt/me');
echo $denied->getStatusCode(), ' ', $denied->getBody(), "\n";
// 401 {"type":"about:blank","title":"Unauthorized","status":401,"detail":"Authorization header missing or not a Bearer token."}

Access and refresh tokens

#

Say what a token is for in its token_use claim when you issue it: Jwt::ACCESS ("access") for the short-lived token that authenticates requests, Jwt::REFRESH ("refresh") for the long-lived one that only gets a new access token. JwtMiddleware and the JwtAuth driver accept access tokens only (Jwt::isAccessToken($claims)): a refresh token, or any other token_use, gets 401. A token issued without token_use still passes unless a _type, typ or type claim marks it as a refresh token, so tokens from Jwt::encode(['sub' => 1], ...) keep working; refresh tokens from controllers make:auth wrote before 1.0.0 ("_type": "refresh") are refused.

PHP
use Taphra\Auth\Jwt;

$access  = Jwt::encode(['sub' => 1, 'token_use' => Jwt::ACCESS], $secret, 900);
$refresh = Jwt::encode(['sub' => 1, 'token_use' => Jwt::REFRESH], $secret, 604800);

echo docs_request('GET', '/jwt/me', [], ['Authorization' => "Bearer $access"])->getBody(), "\n";
// {"user_id":1}

$refused = docs_request('GET', '/jwt/me', [], ['Authorization' => "Bearer $refresh"]);
echo $refused->getStatusCode(), ' ', json_decode((string) $refused->getBody(), true)['detail'], "\n";
// 401 The token is not an access token.

var_dump(Jwt::isRefreshToken(Jwt::decode($refresh, $secret)));   // bool(true)

The refresh endpoint is the one place a refresh token works: leave it out of the middleware (list it in $exclude, or keep it outside the route group), decode the token yourself and check Jwt::isRefreshToken($claims) before issuing a new access token. php taphra make:auth writes such a controller.

Issue the token from a login action that is not behind the middleware (or list its path in $exclude), after checking the password as in Logging in with a session.

The JwtAuth driver

#

Taphra\Auth\JwtAuth makes Auth::check(), Auth::user() and policies work from the bearer token, adds a unique jti and token_use: access to every token it issues, refuses refresh tokens as JwtMiddleware does, and revokes tokens on logout. It needs firebase/php-jwt 7.2 or later (6.10 and later have the same API, but Composer's audit blocks the 6.x releases):

Shell
composer require firebase/php-jwt:^7.2
PHP
// app/bootstrap.php
use Taphra\Auth;
use Taphra\Auth\JwtAuth;

Auth::setDriver(new JwtAuth([
    'secret' => (string) getenv('JWT_SECRET'),   // at least 32 bytes for HS* algorithms
    'algo'   => 'HS256',                         // default
    'ttl'    => 900,                             // seconds, default 3600
]));
PHP
// In the login action, after the password check:
$token = Auth::issueToken($user->only(['id', 'role']));   // return it to the client

// In later requests (Authorization: Bearer <token>):
Auth::check();           // true for a valid, unexpired, unrevoked token
Auth::user('role');      // claims, including jti and exp
Auth::logout();          // revokes this token until it would have expired
Auth::revokeToken(Auth::user('jti'), max(0, Auth::user('exp') - time()));   // for example after a password change

Revoked token IDs live in the application cache. With several servers, use a shared cache backend (Redis) so a revocation applies everywhere.

Policies

#

A policy decides what a user may do with one kind of resource. Put it in app/Policies/, named after the resource: PostPolicy for 'Post'. Each public method is an ability; it receives the current user (Auth::user(), null for a guest) and, when given, the resource. before() runs first: return true to allow everything, false to deny everything, or null to ask the ability method.

PHP
// app/Policies/PostPolicy.php
namespace App\Policies;

use Taphra\Auth\Policy;

class PostPolicy extends Policy
{
    public function before(mixed $user): ?bool
    {
        return ($user['role'] ?? null) === 'admin' ? true : null;
    }

    public function create(?array $user): bool
    {
        return $user !== null;
    }

    public function update(?array $user, array $post): bool
    {
        return $user !== null && $user['id'] === $post['user_id'];
    }
}
PHP
use Taphra\Auth;

$post = ['id' => 10, 'user_id' => 2, 'title' => 'Not yours'];

Auth::login(['id' => 2, 'name' => 'Bob', 'role' => 'author']);
var_dump(Auth::can('update', 'Post', $post));               // bool(true): Bob owns it

Auth::login(['id' => 3, 'name' => 'Carol', 'role' => 'author']);
var_dump(Auth::can('update', 'Post', $post));               // bool(false)
var_dump(Auth::cannot('update', 'Post', $post));            // bool(true)

Auth::login(['id' => 1, 'name' => 'Alice', 'role' => 'admin']);
var_dump(Auth::can('update', 'Post', $post));               // bool(true): before() lets admins through

In a controller, $this->authorize('update', 'Post', $post) throws Taphra\Exceptions\ForbiddenException when the answer is no (the framework answers 403), and $this->can(...) returns the boolean. An ability the policy does not define, or a policy that cannot be found, is a no.

PHP
// app/Controllers/PostEditController.php
namespace App\Controllers;

use Taphra\RestController;

class PostEditController extends RestController
{
    public function update(int $id): string
    {
        $post = ['id' => $id, 'user_id' => 2];   // in an app: PostDataStore::findById($id)
        $this->authorize('update', 'Post', $post);
        return $this->json(['updated' => $id]);
    }
}
PHP
use Taphra\Auth;

Auth::login(['id' => 3, 'name' => 'Carol', 'role' => 'author']);
echo docs_request('PUT', '/posts/10')->getStatusCode(), "\n";   // 403
Auth::login(['id' => 2, 'name' => 'Bob', 'role' => 'author']);
echo docs_request('PUT', '/posts/10')->getBody(), "\n";         // {"updated":10}

PolicyGate::register('Post', PostPolicy::class) maps a resource to a policy explicitly, and PolicyGate::setUserResolver(fn () => ...) changes where the user comes from, for example JwtMiddleware::payload() with JwtMiddleware (both in Taphra\Auth\PolicyGate).

Password reset and email verification

#

Both work with single-purpose tokens kept in the application cache (hashed, per email address), so they need no table. Send the token in a link; check it when the link is opened; invalidate it once used.

PHP
use Taphra\Auth;

$reset = Auth::createPasswordResetToken('[email protected]');          // valid 1 hour (ttl argument)
var_dump(Auth::verifyPasswordResetToken('[email protected]', $reset)); // bool(true)
var_dump(Auth::verifyPasswordResetToken('[email protected]', 'guess')); // bool(false)
Auth::invalidatePasswordResetToken('[email protected]');               // after the new password is saved
var_dump(Auth::verifyPasswordResetToken('[email protected]', $reset)); // bool(false)

$verify = Auth::createVerificationToken('[email protected]');            // valid 24 hours
var_dump(Auth::emailVerificationPending('[email protected]'));           // bool(true)
var_dump(Auth::verifyEmailToken('[email protected]', $verify));          // bool(true)
Auth::invalidateVerificationToken('[email protected]');

Limit how often the endpoints that send these emails can be called (per address and per IP), so they cannot be used to flood an inbox.

Two-factor authentication

#

Time-based one-time passwords (TOTP, RFC 6238) work with authenticator apps. Generate a secret when the user turns two-factor on, show it as a QR code of the provisioning URI, and ask for a code at each login after the password.

PHP
use Taphra\Auth;
use Taphra\Auth\Totp;

$secret = Auth::generateTotpSecret();                 // Base32, 160 bits: store it encrypted
echo Auth::totpProvisioningUri($secret, '[email protected]', 'MyApp'), "\n";
// otpauth://totp/MyApp%3Aalice%40example.com?secret=...&issuer=MyApp&algorithm=SHA1&digits=6&period=30

$code = Totp::generate($secret);                      // what the user's app shows right now
var_dump(Auth::verifyTotp($secret, $code));           // bool(true)
var_dump(Auth::verifyTotp($secret, $code));           // bool(false): a code works once

verifyTotp() accepts the previous and next 30-second step for clock drift ($window = 1), and claims each accepted step in the application cache with an atomic add, so a code cannot be used twice, even by two requests at the same moment. A plain PSR-16 cache handed to Auth::setCacheDriver() has no atomic add: then the check is a read followed by a write, and two simultaneous requests could both pass. It fails closed: when the cache cannot be read or written, it returns false. Limit wrong codes per account with Totp::setAttemptLimiter(RateLimiter::make('totp', 5, 300)); while the limit is reached, every code is refused.

Backup codes let a user in when the phone is lost. Show the plain codes once, store only their hashes, and mark a code used after it matches:

PHP
use Taphra\Auth;

$codes  = Auth::generateBackupCodes();      // 10 codes
$hashes = Auth::hashBackupCodes($codes);    // store these

$matched = '';
var_dump(Auth::verifyBackupCode($codes[3], $hashes, $matched));   // bool(true)
var_dump($matched === $hashes[3]);                                // bool(true): mark this hash used

Encrypt the TOTP secret at rest with Crypt::encrypt() (see Security); someone who reads a plain secret can generate valid codes.

Sessions

#

Taphra\Session wraps PHP sessions; values live under one key of $_SESSION, so they do not collide with other libraries.

PHP
use Taphra\Session;

Session::start();                 // also started on demand by Auth, CSRF tokens and flash data
Session::set('cart_id', 42);
Session::get('cart_id');          // 42
Session::get('missing', 'none');  // 'none'
Session::exists('cart_id');       // true
Session::delete('cart_id');
Session::regenerateId();          // new ID, same data (Auth::login() does this for you)
Session::destroy();

Settings in app/Config/app.yml:

YAML
all:
  session:
    method: file          # file (PHP's handler) or database
    # config: app_master  # with method: database, the connection; the table is created on first use
    # table: sessions
    timeout: 7200         # seconds; else session.cookie_lifetime, then session.gc_maxlifetime from php.ini
    # cookie:             # overrides for the session cookie
    #   domain: .example.com
    #   samesite: Strict

The session cookie is HttpOnly, SameSite=Lax and, on HTTPS, Secure; PHP runs in strict mode with cookies only. The details are in Security.