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

# Secure Lumen APIs with API Key Authentication

Secure your Lumen API using a shared secret.

## How Zuplo Handles It

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

## Lumen Backend Code

```php
// Middleware to validate shared secret header
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);
        }

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

        return $next($request);
    }
}

// In your bootstrap/app.php, register the middleware
$app->routeMiddleware([
    'validate.shared.secret' => App\Http\Middleware\ValidateSharedSecret::class,
]);

// Example route protected by the middleware
$router->get('/protected', ['middleware' => 'validate.shared.secret', function () use ($router) {
    return response()->json(['message' => 'Access granted']);
}]);
```

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