Authentication

Implement Authorization and Access Control in PHP

Distinguish authentication from authorization and enforce resource-level permissions on every protected operation.

Authentication is not authorization

Authentication establishes who a user is. Authorization decides what that user may do. A logged-in user should not automatically access every record.

Check roles on the server

function requireRole(array $user, string $role): void
{
    if (!in_array($role, $user['roles'] ?? [], true)) {
        http_response_code(403);
        exit('Forbidden.');
    }
}

requireRole($currentUser, 'admin');

Roles must come from trusted server-side state, not from a form field or query parameter.

Check record ownership

$stmt = $pdo->prepare(
    'SELECT id, owner_id FROM documents WHERE id = :id'
);
$stmt->execute(['id' => $documentId]);
$document = $stmt->fetch();

if (!$document ||
    (int) $document['owner_id'] !== (int) $currentUser['id']) {
    http_response_code(404);
    exit('Not found.');
}

Apply checks to every route

Protect list, detail, edit, delete, export, download, and API endpoints. Hiding a button in the interface is not access control. Use deny-by-default rules.