How To Implement Custom Api Key Authentication In Laravel 11/12 | Step-By-Step Guide
Published on March 9, 2025 by Dinesh Uprety

How to Implement Custom API Key Auth in Laravel 11/12
In this guide, you’ll learn how to implement custom API key authentication in Laravel 11 or 12. We’ll create
middleware to authenticate requests using an API key sent in the X-API-KEY
header.
Prerequisites
Before starting, ensure you have the following:
- PHP 8.3+
- Composer
- Laravel 11/12
- Postman (for testing)
- A text editor (VS Code, Sublime Text, etc.)
What is an API Key?
An API key is a unique identifier used to authenticate API requests. It’s typically a long string passed in headers to control access and track usage. API keys are often combined with other authentication methods like OAuth or JWT for added security.
Step 1: Generate an API Key
First, generate a secure API key using Laravel’s Str::random()
method.
-
Open your terminal and run:
php artisan tinkerStr::random(64);Example output:
=> "vYNLgAz2gfLcouyBpxVQ83B9b3bdJUMBCXXEiU6RfOTD2iGiQcsFhfoF4rnhAigl" -
Add the generated API key to your
.env
file:APP_API_KEY=vYNLgAz2gfLcouyBpxVQ83B9b3bdJUMBCXXEiU6RfOTD2iGiQcsFhfoF4rnhAigl -
Reference the key in
config/app.php
:// config/app.phpreturn [// ...'app_api_key' => env('APP_API_KEY'),];
💡 Pro Tip: Run
php artisan config:cache
to refresh the config cache after updating.env
.
Step 2: Create a middleware
Next, create middleware to validate the API key.
-
Generate the middleware:
php artisan make:middleware ApiKeyMiddleware -
Add validation logic:
// app/Http/Middleware/ApiKeyMiddleware.php<?phpdeclare(strict_types=1);namespace App\Http\Middleware;use Illuminate\Http\Request;use Symfony\Component\HttpFoundation\Response;final class ApiKeyMiddleware{/*** Handle an incoming request.** @param Closure(Request): (Response) $next*/public function handle(Request $request, Closure $next): Response{$apiKey = $request->header('X-API-KEY');// Validate the API keyif (!$apiKey || $apiKey !== config('app.app_api_key')) {return response()->json(['error' => 'Unauthorized'], 401);}return $next($request);}} -
Register the middleware in
bootstrap/app.php
:// bootstrap/app.php<?phpdeclare(strict_types=1);use App\Http\Middleware\ApiKeyMiddleware;use Illuminate\Foundation\Application;use Illuminate\Foundation\Configuration\Exceptions;use Illuminate\Foundation\Configuration\Middleware;return Application::configure(basePath: dirname(__DIR__))->withRouting(web: __DIR__.'/../routes/web.php',api: __DIR__.'/../routes/api.php',health: '/up',)->withMiddleware(function (Middleware $middleware): void {$middleware->alias(['api.key' => ApiKeyMiddleware::class,]);})->withExceptions(function (Exceptions $exceptions): void {//})->create();
Step 3: Protect Routes
Apply the middleware to your API routes in routes/api.php
:
// routes/api.php use Illuminate\Support\Facades\Route; Route::middleware('api.key')->group(function () { Route::get('/secure', function () { return response()->json([ 'message' => 'Authenticated!' ], 200); });});
Step 4: Test with Postman
- Open Postman.
- Set the
X-API-KEY
header with your API key. - Send a request to the
/secure
endpoint - If the key matches, you’ll receive a
200 OK
response. Otherwise, you’ll get a401 Unauthorized
error.
Best Practices
-
Store API keys securely: Always use
.env
for sensitive data. - Rotate keys periodically: Regularly update API keys to minimize risks.
- Use HTTPS: Encrypt API requests to prevent key interception.
Conclusion
Implementing custom API key authentication in Laravel 11/12 is a straightforward way to secure your APIs. By following this guide, you can control access, protect resources, and ensure only authorized users can interact with your application.
Start securing your Laravel APIs today! 🚀