Skip to content
Nav

Protecting routes

composer require langsys/laravel-api-keys
Packagist version Monthly downloads License PHP 8.2+ Laravel 10 / 11 / 12

Apply the api-key middleware (registered automatically):

Route::middleware('api-key')->group(function () {
Route::get('/projects', [ProjectController::class, 'index']);
Route::post('/projects', [ProjectController::class, 'store']); // requires a `write` key
});

The client sends the key in the X-Api-Key header (configurable). The middleware:

  • rejects missing (401), unknown (401), and inactive (403) keys;
  • enforces read/write scope — read keys may only make GET/HEAD/OPTIONS requests, ip_write keys may write only from an allow-listed address (disable via enforce_read_write);
  • stamps an X-Request-ID on the request and response for tracing;
  • exposes the authenticated key on $request->attributes->get('api_key'), and the request id on $request->attributes->get('api_key_request_id').

The request id is exposed as an attribute as well as a header because the header can be overwritten by other middleware. The package always mints the id itself and never honours a caller-supplied X-Request-ID, so the attribute is safe to use as a correlation or lookup key; the header is not.

Feedback