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

# Secure Hummingbird APIs with API Key Authentication

Secure your Hummingbird API using a shared secret.

## How Zuplo Handles It

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

## Hummingbird Backend Code

```swift
import Hummingbird
import HummingbirdFoundation
import Crypto

struct ValidateSharedSecret: HBMiddleware {
    func apply(to request: HBRequest, next: HBResponder) -> EventLoopFuture<HBResponse> {
        // Retrieve shared secret from environment variable
        guard let expectedSecret = ProcessInfo.processInfo.environment["SHARED_SECRET"] else {
            return request.failure(HBHTTPResponseError(.internalServerError, message: "Server configuration error"))
        }

        // Retrieve the header
        guard let secret = request.headers["x-shared-secret"].first else {
            return request.failure(HBHTTPResponseError(.unauthorized, message: "No secret provided"))
        }

        // Compare secrets using a timing-safe method
        let expectedSecretData = [UInt8](expectedSecret.utf8)
        let secretData = [UInt8](secret.utf8)

        guard expectedSecretData.count == secretData.count,
              expectedSecretData.withUnsafeBytes { expBytes in
                secretData.withUnsafeBytes { secBytes in
                    crypto_compare(expBytes, secBytes) == 0
                }
              } else {
            return request.failure(HBHTTPResponseError(.unauthorized, message: "Invalid secret"))
        }

        return next.respond(to: request)
    }
}

let app = HBApplication()

app.router.add(middleware: ValidateSharedSecret())

app.router.get("/protected") { request -> String in
    return "Access granted"
}

try app.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)
