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

# Secure Litestar APIs with API Key Authentication

Secure your Litestar API using a shared secret.

## How Zuplo Handles It

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

## Litestar Backend Code

```python
import os
from crypto import hmac
from fastapi import HTTPException, Request
from litestar import Litestar, get

# Middleware to validate shared secret header
async def validate_shared_secret(request: Request, call_next):
    expected_secret = os.environ.get("SHARED_SECRET")
    if not expected_secret:
        raise HTTPException(status_code=500, detail="Server configuration error")

    secret = request.headers.get("x-shared-secret")
    if not secret:
        raise HTTPException(status_code=401, detail="No secret provided")

    # Use timing-safe comparison to prevent timing attacks
    if len(secret) != len(expected_secret) or not hmac.compare_digest(secret, expected_secret):
        raise HTTPException(status_code=401, detail="Invalid secret")

    return await call_next(request)

# Create an instance of the Litestar app
app = Litestar(middleware=[validate_shared_secret])

# Example protected route
@app.route("/protected")
async def protected_route(request: Request):
    return {"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)
