---
title: "Secure Laravel APIs with API Key Authentication"
description: "Secure your Laravel API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/php/laravel/secure-header"
framework: "Laravel"
language: "PHP"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure Laravel APIs with API Key Authentication

Secure your Laravel API using a shared secret.

## How Zuplo Handles It

Put Zuplo in front of your Laravel backend to authenticate API keys and forward a shared secret header so your origin only accepts traffic from Zuplo.

## Laravel Backend Code

```php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ValidateSharedSecret
{
    public function handle(Request $request, Closure $next)
    {
        $secret = $request->header('x-shared-secret');
        $expectedSecret = env('SHARED_SECRET');

        if (!$expectedSecret) {
            return response()->json(['error' => 'Server configuration error'], Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        if (!$secret) {
            return response()->json(['error' => 'No secret provided'], Response::HTTP_UNAUTHORIZED);
        }

        if (!hash_equals($expectedSecret, $secret)) {
            return response()->json(['error' => 'Invalid secret'], Response::HTTP_UNAUTHORIZED);
        }

        return $next($request);
    }
}

// Kernel.php
// Add the middleware to the routeMiddleware array
protected $routeMiddleware = [
    // ...
    'validate.shared.secret' => \App\Http\Middleware\ValidateSharedSecret::class,
];

// web.php or api.php
// Protect your route with the middleware
Route::get('/protected', function () {
    return response()->json(['message' => 'Access granted']);
})->middleware('validate.shared.secret');
```

## Example Request

```bash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
