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

# Secure CherryPy APIs with API Key Authentication

Secure your CherryPy API using a shared secret.

## How Zuplo Handles It

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

## CherryPy Backend Code

```python
import cherrypy
import os
import hmac
import hashlib

# Middleware to validate shared secret header
def validate_shared_secret():
    def wrapper(handler):
        def check_secret(*args, **kwargs):
            request = cherrypy.request
            secret = request.headers.get("X-Shared-Secret")
            expected_secret = os.environ.get("SHARED_SECRET")

            if not expected_secret:
                raise cherrypy.HTTPError(500, "Server configuration error")

            if not secret:
                raise cherrypy.HTTPError(401, "No secret provided")

            # Use timing-safe comparison to prevent timing attacks
            if not hmac.compare_digest(secret, expected_secret):
                raise cherrypy.HTTPError(401, "Invalid secret")

            return handler(*args, **kwargs)
        return check_secret
    return wrapper

class ProtectedService:
    @cherrypy.expose
    @validate_shared_secret()
    def protected(self):
        return {"message": "Access granted"}

if __name__ == '__main__':
    cherrypy.tree.mount(ProtectedService(), '/')
    cherrypy.config.update({'server.socket_port': 8080, 'engine.autoreload.on': False})

    cherrypy.engine.start()
    cherrypy.engine.block()
```

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