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

# Secure Kitura APIs with API Key Authentication

Secure your Kitura API using a shared secret.

## How Zuplo Handles It

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

## Kitura Backend Code

```swift
import Kitura
import Foundation
import LoggerAPI
import SwiftJWT

// Middleware to validate shared secret header
func validateSharedSecret(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) {
    guard let expectedSecret = ProcessInfo.processInfo.environment["SHARED_SECRET"] else {
        Log.error("Server configuration error: SHARED_SECRET not set")
        response.status(.internalServerError).send(json: ["error": "Server configuration error"])
        return
    }

    guard let secret = request.headers["X-Shared-Secret"] else {
        response.status(.unauthorized).send(json: ["error": "No secret provided"])
        return
    }

    // Use timing-safe comparison to prevent timing attacks
    if secret.count != expectedSecret.count || !CryptoUtils.constantTimeEquals(expectedSecret, secret) {
        response.status(.unauthorized).send(json: ["error": "Invalid secret"])
        return
    }

    next()
}

// Setup Kitura router
let router = Router()

// Example protected route
router.get("/protected", handler: validateSharedSecret) { request, response, next in
    response.send(json: ["message": "Access granted"])
    next()
}

// Start the Kitura server
Kitura.addHTTPServer(onPort: 8080, with: router)
Kitura.run()
```

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