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

# Secure Flask APIs with API Key Authentication

Secure your Flask API using a shared secret.

## How Zuplo Handles It

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

## Flask Backend Code

```python
from flask import Flask, request, jsonify, abort
import hmac
import os

app = Flask(__name__)

def validate_shared_secret():
    def decorator(f):
        def wrapper(*args, **kwargs):
            secret = request.headers.get("X-Shared-Secret")
            expected_secret = os.getenv("SHARED_SECRET")

            if expected_secret is None:
                abort(500, description="Server configuration error")

            if not secret:
                abort(401, description="No secret provided")

            # Use hmac.compare_digest for timing-safe comparison
            if not hmac.compare_digest(secret, expected_secret):
                abort(401, description="Invalid secret")

            return f(*args, **kwargs)
        wrapper.__name__ = f.__name__
        return wrapper
    return decorator

@app.route('/protected')
@validate_shared_secret()
def protected():
    return jsonify(message="Access granted")

if __name__ == "__main__":
    app.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)
