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

# Secure Sanic APIs with API Key Authentication

Secure your Sanic API using a shared secret.

## How Zuplo Handles It

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

## Sanic Backend Code

```python
from sanic import Sanic, response
from sanic.request import Request
from sanic.exceptions import SanicException
import os
import hmac
import hashlib

app = Sanic("SecureAPI")

# Middleware to validate shared secret header
async def validate_shared_secret(request: Request):
    expected_secret = os.getenv("SHARED_SECRET")

    if not expected_secret:
        raise SanicException("Server configuration error", status_code=500)

    secret = request.headers.get("x-shared-secret")

    if not secret:
        raise SanicException("No secret provided", status_code=401)

    # Use HMAC to ensure a timing-safe comparison
    if not hmac.compare_digest(secret, expected_secret):
        raise SanicException("Invalid secret", status_code=401)

# Add middleware
@app.on_request
async def check_secret_middleware(request: Request):
    await validate_shared_secret(request)

# Example protected route
@app.get("/protected")
async def protected_route(request: Request):
    return response.json({"message": "Access granted"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)
```

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