Laravel API Secure: A Comprehensive Guide to Securing Your Laravel API
1 min readApr 9, 2023
Create an environment variable for your API key by adding the following line to your .env
file:
API_KEY=your_api_key_here
In your config/services.php
file, add a new entry for your API key:
'custom_api' => [
'key' => env('API_KEY'),
],
Create a new middleware using the php artisan make:middleware
command:
php artisan make:middleware ApiKeyMiddleware
In the handle()
method of your new middleware, check if the API key in the request matches the API key in your environment variables:
public function handle(Request $request, Closure $next)
{
$apiKey = $request->header('X-API-KEY');
if ($apiKey !== config('services.custom_api.key')) {
return response()->json(['error' => 'Invalid API key.'], 401);
}
return $next($request);
}
Register your middleware in app/Http/Kernel.php
by adding it to the $routeMiddleware
array:
protected $routeMiddleware = [
// ...
'api_key' => \App\Http\Middleware\ApiKeyMiddleware::class,
];
Apply the middleware to the routes that you want to protect:
Route::group(['middleware' => ['api_key']], function () {
Route::get('/protected', function () {
return response()->json(['data' => 'This route is protected.']);
});
});
That’s it! Now your API is protected and only requests with a valid API key will be allowed.
I hope it can help you…