Route Guards¶
Route guards act like security checkpoints on specific routes. Before LacePHP hands control to your controller, it instantiates the guard you specify and calls its check() method. If the guard returns false, the request is blocked (often with an HTTP 401 or 403) and your controller never runs.
Why guards matter¶
Fine-grained security Protect individual routes without writing if statements in your controllers.
No database needed Useful for small teams or internal APIs where you can supply tokens via environment variables.
Consistent handling Every guarded route uses the same logic and error responses.
Configuration in config/lace.php¶
In your PHP config you define which guard to use by default and supply any secrets:
return [
// …
'auth' => [
'guard' => env('AUTH_GUARD', 'token'),
'tokens' => [
env('TOKEN_SECRET1', 'secret123'),
env('TOKEN_SECRET2', 'anotherSecret456'),
],
],
// …
];
Here: - guard sets the default guard type (token, signature or hmac). - tokens is an array of valid bearer tokens for the token guard.
Applying a Guard to a Route¶
Use the special _guard key in your route’s middleware array:
use Lacebox\Strap\Guards\ShoeTokenGuard;
$router->addRoute(
'GET',
'/secure-endpoint',
[SecureController::class, 'index'],
[
'_guard' => 'token', # invokes ShoeTokenGuard
CorsKnots::class, # plus any other middleware
]
);
LacePHP will:
Instantiate the guard class matching the string (‘token’ → ShoeTokenGuard)
Call its check() method
If true, proceed to middleware and controller
If false, immediately return an “Unauthorized” response
Built-In Guards Reference¶
Guard |
Class |
Usage Key |
Description |
---|---|---|---|
Token |
|
|
Checks for a Bearer token in the Authorization header and compares it to your tokens from config. |
Signature |
|
|
Verifies an HMAC signature passed as a signature query parameter using your secret. |
HMAC |
|
|
Validates an HMAC signature from the X-HMAC-SIGNATURE header against the raw request body. |
By using route guards, you can secure endpoints cleanly, avoid scattered if checks, and leverage simple configuration without a full user database.