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: .. code-block:: php 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: .. code-block:: php 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: 1. Instantiate the guard class matching the string (`'token'` → `ShoeTokenGuard`) 2. Call its `check()` method 3. If `true`, proceed to middleware and controller 4. If `false`, immediately return an “Unauthorized” response Built-In Guards Reference ------------------------- .. list-table:: :header-rows: 1 :widths: 20 40 25 35 * - **Guard** - **Class** - **Usage Key** - **Description** * - Token - ``ShoeTokenGuard::class`` - ``'_guard' => 'token'`` - Checks for a Bearer token in the `Authorization` header and compares it to your `tokens` from config. * - Signature - ``ShoeSignatureGuard::class`` - ``'_guard' => 'signature'`` - Verifies an HMAC signature passed as a `signature` query parameter using your secret. * - HMAC - ``ShoeHmacGuard::class`` - ``'_guard' => '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. | |