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

# Secure Phalcon APIs with API Key Authentication

Secure your Phalcon API using a shared secret.

## How Zuplo Handles It

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

## Phalcon Backend Code

```php
use Phalcon\Mvc\Micro;
use Phalcon\Http\Response;
use Phalcon\Config;

// Load environment variables
$sharedSecret = getenv('SHARED_SECRET');

if (!$sharedSecret) {
    throw new Exception('Server configuration error: SHARED_SECRET not set.');
}

$app = new Micro();

// Middleware to validate shared secret header
$app->before(function () use ($app, $sharedSecret) {
    $request = $app->request;
    $response = new Response();

    $secret = $request->getHeader('X-Shared-Secret');

    if (!$secret) {
        $response->setStatusCode(401, 'Unauthorized')
                 ->setJsonContent(['error' => 'No secret provided'])
                 ->send();
        return false;
    }

    // Use hash_equals to prevent timing attacks
    if (!hash_equals($sharedSecret, $secret)) {
        $response->setStatusCode(401, 'Unauthorized')
                 ->setJsonContent(['error' => 'Invalid secret'])
                 ->send();
        return false;
    }

    return true;
});

// Example route protected by the middleware
$app->get('/protected', function () {
    return json_encode([
        'message' => 'Access granted'
    ]);
});

// Error handling
$app->error(function ($exception) use ($app) {
    $response = new Response();
    $response->setStatusCode(500, 'Internal Server Error')
             ->setJsonContent(['error' => $exception->getMessage()])
             ->send();
    return false;
});

$app->handle($_SERVER["REQUEST_URI"]);
```

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