Authentication
Last updated: 2026-10-28
The canvas-authorization package provides a complete authentication scaffold for Canvas applications. A single CLI command installs login, registration, and route protection — configured for your template engine automatically.
Installation
Add the package to your project:
composer require quellabs/canvas-authorization Run the installer via Sculpt:
php vendor/bin/sculpt install:auth The installer copies the following files into your project:
- src/Controllers/AuthenticationController.php — Login, logout, and registration routes
- src/Controllers/AuthenticatedController.php — Base controller that protects everything extending it
- src/Errors/AuthErrorHandler.php — Turns authentication failures into a redirect to the login page
- src/Validation/LoginFormValidator.php — Server-side login validation
- src/Validation/RegistrationFormValidator.php — Server-side registration validation
- src/Entities/UserEntity.php — ORM entity representing a user, implementing
AccountEligibilityInterface - src/Exceptions/UserCreationException.php — Typed exception for registration failures
- templates/login.{ext} — Login form template
- templates/registration_form.{ext} — Registration form template
Once installed, these files are yours to modify. Two aspects that do the actual authentication work — SessionAuthenticationAspect and AccountEligibilityAspect — are not copied; your app uses them directly from the package (see The Two Aspects below).
Template Engine Detection
The installer reads config/app.php and copies the correct template stubs for your configured engine:
- Smarty —
login.tpl,registration_form.tpl - Blade —
login.blade.php,registration_form.blade.php - Latte —
login.latte,registration_form.latte - Twig —
login.twig,registration_form.twig
Options
Pass --force to overwrite existing files without being prompted:
php vendor/bin/sculpt install:auth --force Database Setup
After installation, generate and run the migration to create the users table:
php vendor/bin/sculpt make:migrations
php vendor/bin/sculpt quel:migrate How Authentication Works
Login Flow
The AuthenticationController handles the full login lifecycle:
- A
GET /loginrequest renders the login form - A
POST /loginsubmission is intercepted byValidateAspect, which runsLoginFormValidator - If validation fails, the form is re-rendered with field-level errors
- If validation passes, the username and password are checked against the database
- On success, three session keys are written and the user is redirected to
/ - On failure, the form is re-rendered with a generic error to avoid revealing whether the username or password was wrong
/**
* Process login form submission
* @Route("/login", methods={"POST"})
* @InterceptWith(Quellabs\Canvas\Validation\ValidateAspect::class, validator=App\Validation\LoginFormValidator::class)
*/
public function processLogin(Request $request): Response {
if (!$request->attributes->get('validation_passed', true)) {
return $this->render('login.tpl', ['errors' => $request->attributes->get('validation_errors', [])]);
}
$username = $request->request->get('username');
$password = $request->request->get('password');
$user = $this->findUser($username);
if (!$user || !$this->checkPassword($password, $user)) {
return $this->render('login.tpl', ['errors' => ['general' => ['Invalid username or password.']]]);
}
$session = $request->getSession();
$session->set('auth_user_id', $user->getId());
$session->set('auth_time', time());
$session->set('auth_methods', ['pwd']);
return new RedirectResponse('/');
} Registration Flow
Registration follows the same pattern as login, including writing the same three session keys on success:
- A
GET /registerrequest renders the registration form - A
POST /registersubmission is intercepted byValidateAspectwithRegistrationFormValidator - Server-side password confirmation is checked after validation
- If the username is already taken, the form is re-rendered with an error
- On success, the new user is persisted, logged in automatically, and redirected to
/
Session Management
Authentication state is stored in the session under three keys. Session handling is provided by Symfony HttpFoundation — Canvas uses its defaults without wrapping or extending the session layer:
| Session key | Type | Meaning |
|---|---|---|
auth_user_id | mixed | The authenticated user's identifier. Absence means "not logged in." |
auth_time | int | Unix timestamp of when the credential was proven at login. |
auth_methods | string[] | Methods used at login (RFC 8176 names, e.g. pwd). Consumed by step-up authentication. |
// Login — store user identity and when/how it was proven
$session = $request->getSession();
$session->set('auth_user_id', $user->getId());
$session->set('auth_time', time());
$session->set('auth_methods', ['pwd']);
$session->migrate(); // regenerate the session ID — neither aspect does this for you
// Logout — clear all session data
$request->getSession()->clear(); auth_time/auth_methods exist specifically so Quellabs\Canvas\Security\StepUpAuthenticationAspect can require a recent credential proof for sensitive actions — see Step-Up Authentication (Sudo Mode).
Protecting Routes
Extend AuthenticatedController instead of BaseController to protect every action in a controller:
class DashboardController extends App\Controllers\AuthenticatedController {
/**
* @Route("/dashboard", methods={"GET"})
*/
public function index(): Response {
return $this->render('dashboard.tpl');
}
} AuthenticatedController declares its aspects at the class level, so every controller that extends it — and every method in it — is protected automatically, with nothing to declare per route:
/**
* @InterceptWith(Quellabs\CanvasAuthorization\SessionAuthenticationAspect::class, throwOnFailure=true)
* @InterceptWith(Quellabs\CanvasAuthorization\AccountEligibilityAspect::class, userEntityClass=App\Entities\UserEntity::class, throwOnFailure=true)
*/
abstract class AuthenticatedController extends BaseController {
} @InterceptWith on a class applies through the whole inheritance chain — resolved the same way whether it's declared on a class or a method, so a sensitive method can still stack a further, stricter check on top:
class AccountController extends App\Controllers\AuthenticatedController {
/**
* @Route("/account/delete", methods={"POST"})
* @InterceptWith(Quellabs\Canvas\Security\StepUpAuthenticationAspect::class, maxAge=300, requiredMethods={"pwd"})
*/
public function deleteAccount(): Response {
// Only reached with a logged-in, eligible account, authenticated within the last 5 minutes via 'pwd'
}
} The Two Aspects Behind AuthenticatedController
AuthenticatedController is not itself a single aspect — it composes two, each with one responsibility, run in this order:
| Aspect | Responsibility | On success |
|---|---|---|
SessionAuthenticationAspect | Is auth_user_id present in the session at all? | Publishes session_user_id, auth_time, auth_methods on the request |
AccountEligibilityAspect | Reads session_user_id; is that account still eligible (not banned or deleted)? | Lets the request continue |
Both are used directly from the package — not copied into your application — so they receive fixes via composer update rather than being frozen at generation time. AccountEligibilityAspect only needs your user entity to implement one method:
namespace Quellabs\CanvasAuthorization\Contracts;
interface AccountEligibilityInterface {
public function isBanned(): bool;
} AccountEligibilityAspect re-checks the database at most once per validationInterval seconds (default 300) rather than on every request:
/** @InterceptWith(Quellabs\CanvasAuthorization\AccountEligibilityAspect::class, userEntityClass=App\Entities\UserEntity::class, validationInterval=60, throwOnFailure=true) */ Handling Authentication Failures
Like every authentication aspect in Canvas, neither SessionAuthenticationAspect nor AccountEligibilityAspect builds a Response itself:
- Attribute mode (default): sets
session_errororaccount_eligibility_erroron the request and lets the controller decide how to respond. - Exception mode (
throwOnFailure=true): throwsSessionAuthenticationExceptionorAccountEligibilityException(both HTTP 403/401), which propagates to a registeredErrorHandlerInterface.
AuthenticatedController uses exception mode on both, which is what makes "just extend this class" actually protect a page — the installer scaffolds the handler that turns those exceptions into a redirect:
namespace App\Errors;
use Quellabs\Canvas\Error\ErrorHandlerInterface;
use Quellabs\CanvasAuthorization\Exceptions\AccountEligibilityException;
use Quellabs\CanvasAuthorization\Exceptions\SessionAuthenticationException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class AuthErrorHandler implements ErrorHandlerInterface {
public static function supports(\Throwable $e): bool {
return $e instanceof SessionAuthenticationException || $e instanceof AccountEligibilityException;
}
public function handle(\Throwable $e, Request $request): Response {
return new RedirectResponse('/login');
}
} This file is copied into src/Errors/ — Canvas discovers ErrorHandlerInterface implementations by scanning that directory (see Error Handlers). Edit it directly if your login route isn't /login, or if you want to log the failure before redirecting.
Accessing the Authenticated User
Read the user ID that SessionAuthenticationAspect published on the request, rather than the session directly:
public function index(Request $request): Response {
$userId = $request->attributes->get('session_user_id');
$user = $this->em()->find(UserEntity::class, $userId);
return $this->render('dashboard.tpl', ['user' => $user]);
} Customisation
The scaffolded files are standard Canvas classes you're free to modify:
- UserEntity — Add fields such as
email,created_at, orrole - AuthErrorHandler — Change the redirect target, log failures, or return JSON for an API
- LoginFormValidator — Adjust validation rules to match your requirements
- Templates — Restyle to match your application's design
Customizing Eligibility Logic
If AccountEligibilityAspect's constructor parameters and AccountEligibilityInterface aren't enough to express your desired revalidation strategy — for example, checking multiple flags or a subscription status rather than a single isBanned() method — eject a fully editable local copy instead of using the package class:
php vendor/bin/sculpt make:auth-aspect This copies the aspect's logic into src/Aspects/AccountEligibilityAspect.php. Point AuthenticatedController (or any controller) at App\Aspects\AccountEligibilityAspect::class instead of the package class. It's now your code — it no longer receives fixes or changes from quellabs/canvas-authorization.
File Conflicts
If any of the target files already exist, the installer prompts before overwriting each one. Pass --force to skip prompts and overwrite all files unconditionally.
File already exists: src/Controllers/AuthenticationController.php. Overwrite? [y/N] See Also
- JWT Authentication — the stateless equivalent for APIs, using the same
auth_time/auth_methodsattribute contract - Step-Up Authentication (Sudo Mode) — requiring a recent, specific-method credential proof for sensitive actions
- Error Handlers — how
ErrorHandlerInterfacediscovery and dispatch works
Frequently Asked Questions
Do SessionAuthenticationAspect or AccountEligibilityAspect ever return a Response directly?
No — never. Both only set a request attribute or throw an exception; building the actual redirect or error response is left entirely to your app's ErrorHandlerInterface (the scaffolded AuthErrorHandler) or to your controller reading the attribute. This is a deliberate guarantee, not an implementation detail that might change.
What happens if my user entity doesn't implement AccountEligibilityInterface?
AccountEligibilityAspect throws an InvalidArgumentException immediately when it's constructed — not on the first request that needs re-validation. A configuration mistake like this surfaces right away rather than as a confusing failure deep inside request handling later.
Does Canvas handle session expiry or idle timeout for me?
No — that's intentionally out of scope for SessionAuthenticationAspect. Session lifetime is governed entirely by your session storage's own configuration (e.g. session.gc_maxlifetime), not by anything this package adds.
What happens when AccountEligibilityAspect determines a user is banned or deleted?
It clears the session — auth_user_id, auth_time, auth_methods, and its own revalidation timestamp — in addition to reporting the failure. That effectively logs the user out rather than just blocking the one request that triggered the check.
Is the "once per validationInterval" database re-check tracked globally, or per session?
Per session — the last-validated timestamp is stored in the session itself, not in a shared store keyed by user ID. Logging in again, or on another device, starts that interval fresh rather than inheriting a previous session's timer.
Can I protect a single route instead of an entire controller?
Yes — add the same @InterceptWith annotations directly to one method instead of extending AuthenticatedController. Canvas resolves class-level and method-level @InterceptWith declarations the same way, so there's nothing special about using them outside the scaffolded base controller.
Summary
Canvas authentication is designed to get you started quickly without locking you in:
- One Command —
install:authscaffolds everything needed for login and registration - Engine Aware — Templates copied for your configured engine automatically
- Single-Responsibility Aspects — Session validity and account eligibility are checked by two separate, package-owned aspects, composed once on a shared base controller
- Uniform Failure Handling — Every authentication aspect sets a request attribute or throws; nothing builds a
Responseitself, kept consistent with an app-owned error handler - Ejectable When Needed —
make:auth-aspectgives you a fully owned copy the moment the package's interface isn't enough