Zuplo

API Key Authentication

Secure Your Litestar API with API Keys

The Zuplo API Gateway protects your backend API from unauthorized access, abuse, and overload. Add API key authentication to your Litestar API in minutes.

Secure Access

Authenticate every request before it reaches your backend.

Control Costs

Set rate limits and quotas to prevent runaway usage.

Ensure Reliability

Shield your backend from overload with traffic management.

How it works

The Zuplo API Gateway sits between your clients and your Litestar backend, providing a secure layer of protection and control.

Client
Zuplo API Gateway

Customer VPC

Backend

Step-by-step tutorial

It takes only a few minutes to put Zuplo in front of your Litestar backend, adding API key authentication, and configuring your origin to trust requests from Zuplo using JWT verification.

1

Create a Route in Zuplo

First, create a new route in your Zuplo project that will proxy requests to your Litestar backend. This route will be the entry point for your API consumers.

Creating a route in Zuplo
Learn how to create routes

📄 OpenAPI native. Import your existing OpenAPI spec to instantly create routes and power your API documentation .

2

Add API Key Authentication Policy

Add the API Key Authentication policy to your route. This policy validates incoming API keys and ensures only authorized consumers can access your API.

Adding API Key Authentication policy in Zuplo
API Key Authentication docs

🔐 Leaked key? No problem. As a GitHub Secret Scanning partner, Zuplo can automatically revoke exposed keys before they can be exploited.

3

Enable the JWT Service Plugin

Enable the JWT Service Plugin in your Zuplo project. This plugin generates JWTs that your origin API can validate, creating a secure trust relationship between Zuplo and your backend.

TypeScriptmodules/zuplo.runtime.ts
export function runtimeInit(runtime: RuntimeExtensions) {
  // Register the JWT Service Plugin
  runtime.addPlugin(new JwtServicePlugin());
}
JWT Service Plugin docs
4

Secure Your Litestar API with JWT Authentication

Configure your Litestar backend to validate the JWTs issued by Zuplo. This ensures that only requests coming through your Zuplo gateway are accepted.

Python
from litestar import Litestar, get, Request
from litestar.middleware import AbstractMiddleware
from litestar.exceptions import NotAuthorizedException
from jose import jwt
from jose.exceptions import JWTError, ExpiredSignatureError
import requests
from cachetools import TTLCache
from typing import Any

ISSUER = "https://my-api-a32f34.zuplo.api/__zuplo/issuer"
JWKS_URL = f"{ISSUER}/.well-known/jwks.json"
ALGORITHMS = ["RS256"]

# Cache for JWKS keys
jwks_cache = TTLCache(maxsize=10, ttl=600)

def get_jwks():
    if JWKS_URL not in jwks_cache:
        resp = requests.get(JWKS_URL)
        resp.raise_for_status()
        jwks_cache[JWKS_URL] = resp.json()
    return jwks_cache[JWKS_URL]

def get_key(token: str):
    unverified_header = jwt.get_unverified_header(token)
    jwks = get_jwks()
    for jwk in jwks['keys']:
        if jwk['kid'] == unverified_header['kid']:
            return jwt.algorithms.RSAAlgorithm.from_jwk(jwk)
    raise JWTError("Unable to find appropriate key")

async def jwt_auth_middleware(request: Request, call_next: Any) -> Any:
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        raise NotAuthorizedException(detail='No token provided')

    token = auth_header[7:]
    try:
        key = get_key(token)
        payload = jwt.decode(token, key, algorithms=ALGORITHMS, issuer=ISSUER)
        request.state.user = payload
    except ExpiredSignatureError:
        raise NotAuthorizedException(detail='Token has expired')
    except JWTError as e:
        raise NotAuthorizedException(detail=f'Invalid token: {str(e)}')

    return await call_next(request)

@get('/protected')
async def protected_route(request: Request) -> dict:
    return {'message': 'Access granted', 'user': request.state.user}

app = Litestar(
    route_handlers=[protected_route],
    middleware=[jwt_auth_middleware]
)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=8000)
5

Call Your API Through Zuplo

Now you can call your API through Zuplo using an API key. The request will be authenticated at the gateway, and a JWT will be forwarded to your Litestar backend.

Terminalbash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Ready to secure your API?

Get started with Zuplo for free and add API key authentication to your Litestar API in minutes.