Protecting routes
composer require langsys/laravel-api-keys 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 —
readkeys may only makeGET/HEAD/OPTIONSrequests,ip_writekeys may write only from an allow-listed address (disable viaenforce_read_write); - stamps an
X-Request-IDon 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.