Implementing Simple API Key Authentication in Laravel 8
If you need a lightweight authentication mechanism for an internal tool or prototype without the overhead of full OAuth flows, Laravel's built-in request lifecycle is sufficient. You do not need to integrate Passport or Sanctum if your requirements are strictly about validating a static string against a specific list of keys. The goal is to intercept the incoming request, extract the API key from the URI parameters, and return a 401 Unauthorized response if validation fails.
In this scenario, the client includes the key as a query parameter, for example: https://[ipv6-address]/api/endpoint1?apikey=your-secret-key. While passing secrets via URL parameters is generally discouraged in production due to logging risks and potential exposure in browser history, it is perfectly acceptable for a controlled prototype environment.
To implement this, you should leverage the auth middleware or create a custom one that specifically handles the query parameter logic. Creating a dedicated middleware keeps your controllers clean and isolates the validation logic. Define the middleware class within your application directory:
// app/Http/Middleware/CheckApiKey.php
namespace App\Http\Middleware;
use Closure;
class CheckApiKey
{
public function handle($request, Closure $next)
{
// Retrieve the API key from the query parameter
$apiKey = $request->query('apikey');
// Define your list of valid keys.
// In a real scenario, consider fetching these from an environment variable or config file.
$validKeys = [
'proto_key_12345',
'dev_key_67890'
];
if (in_array($apiKey, $validKeys)) {
return $next($request);
}
// Return 401 Unauthorized if the key is missing or invalid
return response()->json(['message' => 'Unauthorized'], 401);
}
}
Once the middleware is created, you must register it in the application's HTTP kernel. Open app/Http/Kernel.php and add the new class to the $routeMiddleware array:
// app/Http/Kernel.php
protected $routeMiddleware = [
// ... existing middleware
'api.key' => \App\Http\Middleware\CheckApiKey::class,
];
With the middleware registered, you can apply it globally to all API routes or selectively to specific route groups. To protect the entire /api namespace as requested, use a route group in your routes/api.php file:
// routes/api.php
use Illuminate\Support\Facades\Route;
Route::middleware(['auth:api.key'])->group(function () {
Route::get('/endpoint1', [EndpointController::class, 'index']);
Route::post('/endpoint2', [EndpointController::class, 'store']);
});
This approach ensures that any request attempting to access these endpoints without a valid apikey parameter receives an immediate 401 response. The middleware runs before the route is dispatched, short-circuiting execution for unauthorized clients.
Security Considerations and Trade-offs
While this solution satisfies the prototype requirement, it is important to acknowledge the limitations inherent in passing secrets via query strings. Query parameters are visible in server logs, browser history, and potentially shared with proxies or load balancers depending on their configuration. If you move from a prototype to production, you will likely need to migrate to Authorization: Bearer <key> headers or use Sanctum for stateless token-based authentication.
Additionally, hardcoding API keys directly in the middleware code is fragile. As your application grows, managing a list of keys becomes unwieldy. A better practice is to store these keys in an environment variable (e.g., API_KEYS) and deserialize them using explode(',', env('API_KEYS')) within the middleware. This keeps secrets out of version control and allows you to rotate access without touching the codebase.
Finally, remember that standard Laravel authentication guards (auth:api) are designed for Sanctum or Passport tokens stored in headers, not raw query parameters. By bypassing those systems entirely with a custom check, you avoid the complexity of user sessions while still maintaining strict access control for your API endpoints.