PHP
Implement API Key Authentication for Incoming API Requests (PHP Laravel)
Secure your API endpoints by implementing a custom middleware for API key authentication in Laravel, verifying keys against a database or configuration.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class ApiKeyAuthenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
// Check for the X-API-KEY header
$apiKey = $request->header('X-API-KEY');
// TODO: Replace with your actual API key validation logic.
// This could be checking against a database table of API keys,
// comparing to an environment variable, or a hardcoded list.
$validApiKeys = ['my_secret_api_key_123', 'another_valid_key_456'];
if (!in_array($apiKey, $validApiKeys)) {
return Response::json([
'message' => 'Unauthorized: Invalid or missing API Key.'
], 401);
}
// API Key is valid, continue with the request
return $next($request);
}
}
// --- How to register and use this middleware in Laravel ---
// 1. Save the above code as app/Http/Middleware/ApiKeyAuthenticate.php
//
// 2. Register the middleware in app/Http/Kernel.php under the $middlewareAliases array:
// 'api_key_auth' => \App\Http\Middleware\ApiKeyAuthenticate::class,
//
// 3. Apply the middleware to your API routes in routes/api.php:
// Route::middleware('api_key_auth')->group(function () {
// Route::get('/secured-data', function () {
// return response()->json(['message' => 'Access granted to secured data!']);
// });
// });
How it works: This PHP snippet provides a Laravel middleware for implementing API key authentication. The `handle` method intercepts incoming requests and checks for the presence and validity of an API key, typically sent in the `X-API-KEY` HTTP header. If the key is missing or does not match a predefined valid key (which should ideally be fetched from a database or environment variable in a real application), it returns an unauthorized (401) JSON response. If the key is valid, the request proceeds to the intended route. Instructions for registering and applying the middleware in Laravel are also provided.