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

# Secure Hug APIs with API Key Authentication

Secure your Hug API using a shared secret.

## How Zuplo Handles It

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

## Hug Backend Code

```python
import hug
import os
import hmac
import hashlib

def validate_shared_secret(shared_secret: hug.types.text):
    expected_secret = os.environ.get('SHARED_SECRET')

    if not expected_secret:
        hug.HTTPInternalServerError("Server configuration error")

    if not shared_secret:
        raise hug.HTTPUnauthorized("No secret provided")

    # Use timing-safe comparison to prevent timing attacks
    if len(shared_secret) != len(expected_secret) or not hmac.compare_digest(shared_secret, expected_secret):
        raise hug.HTTPUnauthorized("Invalid secret")

# Define a middleware using the `validate_shared_secret` function
@hug.authentication.basic(validate_shared_secret)
def shared_secret_authentication(user, password):
    return True

@hug.get('/protected', requires=shared_secret_authentication)
def protected():
    return {"message": "Access granted"}

if __name__ == '__main__':
    hug.API(__name__).http.serve()
```

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