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

# Secure Swoole APIs with API Key Authentication

Secure your Swoole API using a shared secret.

## How Zuplo Handles It

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

## Swoole Backend Code

```php
<?php

use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;

// Secure middleware function
function validateSharedSecret(Request $request, Response $response): bool {
    $secret = $request->header['x-shared-secret'] ?? null;
    $expectedSecret = getenv('SHARED_SECRET');

    if (!$expectedSecret) {
        $response->status(500);
        $response->end(json_encode(['error' => 'Server configuration error']));
        return false;
    }

    if (!$secret) {
        $response->status(401);
        $response->end(json_encode(['error' => 'No secret provided']));
        return false;
    }

    // Use hash_equals for timing-safe comparison
    if (!hash_equals($expectedSecret, $secret)) {
        $response->status(401);
        $response->end(json_encode(['error' => 'Invalid secret']));
        return false;
    }

    return true;
}

// Swoole HTTP server setup
$server = new Server("127.0.0.1", 9501);

$server->on("start", function (Server $server) {
    echo "Swoole HTTP server is started at http://127.0.0.1:9501\n";
});

$server->on("request", function (Request $request, Response $response) {
    if (!validateSharedSecret($request, $response)) {
        return;
    }

    if ($request->server['request_uri'] === '/protected') {
        $response->header('Content-Type', 'application/json');
        $response->end(json_encode(['message' => 'Access granted']));
    } else {
        $response->status(404);
        $response->end('Not Found');
    }
});

$server->start();
```

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