When building APIs with Laravel, securing your endpoints is just as important as designing them. API keys provide a lightweight authentication method that allows trusted clients to access your services without the complexity of full authentication systems. In this blog, we'll explore how to implement API key authentication in Laravel step by step.
Create variables in the .env file, name it whatever you like.
//.env file
APP_API_KEY=G0m30wjzGcnQz78TVXqszfDVVguj5z6v98aTOpN3be5Register the newly created variable. In the root directory of the project, select the config folder and open the app.php.
<?php
use Illuminate\Support\Facades\Facade;
return [
...
'app_api_key' => env('APP_API_KEY'),
];Create a middleware by running in the terminal
php artisan make:middleware ApiKeyMiddlewareConfigure the middleware to check the API key in the request header
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ApiKeyMiddleware
{
/**
* 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)
{
$apiKey = $request->header('X-API-KEY');
\Log::info('API Key received: ' . ($apiKey ?? 'NULL'));
\Log::info('Expected: ' . config('app.app_api_key'));
if(!$apiKey || $apiKey !== config('app.app_api_key')){
return response()->json([
'success' => false,
'message' => 'Unauthorized access.'
], 401);
}
return $next($request);
}
}Add the ApiKeyMiddleware in the route middleware array. In the root directory, go to app\Http\Kernel.php.
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
...other code above...
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
... other middleware ...
'api.key' => \App\Http\Middleware\ApiKeyMiddleware::class,
];
}In the routes\api.php, configure the api endpoints.
<?php
Route::prefix('v1')->middleware('api.key')->group(function () {
... your endpoints here..
});After the API key is implemented, all the request to that endpoints should have "x-api-key" in the request header.