# How to Implement Custom API Key Authentication in Laravel 11/12 | Step-by-Step Guide

By Dinesh Uprety
Published: 2025-03-08
Updated: 2025-03-09
Canonical: https://laranepal.com/blog/how-to-implement-custom-api-key-authentication-in-laravel-1112-step-by-step-guide

# 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 api key?](https://laranepal.com/storage/n5uQq6Hi5gbXPNwTrZvSqDvgalub0jTeQ4qlSQZq.webp)

## 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.

1. Open your terminal and run:

    ```bash
       php artisan tinker
       Str::random(64);
    ```

   Example output:

    ```bash
    => "vYNLgAz2gfLcouyBpxVQ83B9b3bdJUMBCXXEiU6RfOTD2iGiQcsFhfoF4rnhAigl"
    ```

2. Add the generated API key to your `.env` file:

   ```php
   APP_API_KEY=vYNLgAz2gfLcouyBpxVQ83B9b3bdJUMBCXXEiU6RfOTD2iGiQcsFhfoF4rnhAigl
   ```

3. Reference the key in `config/app.php`:

   ```php
   // config/app.php
   
   return [
       // ...
   
       '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.

1. Generate the middleware:

   ```bash
   php artisan make:middleware ApiKeyMiddleware
   ```
2. Add validation logic:

   ```php
   // app/Http/Middleware/ApiKeyMiddleware.php
   
   <?php
   
   declare(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 key
           if (!$apiKey || $apiKey !== config('app.app_api_key')) {
               return response()->json(['error' => 'Unauthorized'], 401);
           }
           return $next($request);
       }
   }
   ```

3. Register the middleware in `bootstrap/app.php`:

   ```php
   // bootstrap/app.php
   
   <?php
   
   declare(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`:

```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

1. Open **Postman**.
2. Set the `X-API-KEY` header with your API key.
3. Send a request to the `/secure` endpoint
4. If the key matches, you’ll receive a `200 OK` response. Otherwise, you’ll get a `401 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! 🚀
