---
title: "Ouro as API middleware"
description: "Using Ouro as your API's authentication and monetization middleware"
date: "2024-08-01"
last_updated: "2025-10-14"
---

This guide outlines the process of configuring your API to use Ouro as an authentication and monetization middleman.
By integrating Ouro, you can streamline several critical aspects of API management:

- **Simplified authentication**: Ouro handles user authentication, reducing the complexity of implementing and maintaining your own auth system.
- **Monetization made easy**: Ouro provides built-in tools for setting up paid routes, usage limits, and billing, allowing you to monetize your API without building a custom billing system.
- **Rate limiting**: By using Ouro as a proxy, you add an extra layer of security between your API and end-users.
- **Usage analytics**: Get insights into how your API is being used.

<Image
  src="/images/guides/middleman.svg"
  width={3000}
  height={830}
  className="p-4 dark:invert"
  alt="A diagram of how the Ouro middleware sits in between your users and your API."
/>

We've designed this process so that your end users will need to make minimal changes to their existing configuration:

- A new base URL to use
- An API key to pass with requests as an Auth header

Everything else, including parameter and request body configuration will be exactly the same as you originally designed it.

## 1. Getting started

To start using Ouro as your API middleman, you'll need to [sign up for an Ouro account](/signup) if you haven't already.

Next, you'll need to modify your API to work with Ouro.
Your API will need to verify that incoming requests are coming from Ouro and to only respond to those requests.

Finally, you'll need to [add your service to Ouro](/services/create) and configure any desired pricing and usage limits.

See our guide for more details on how to add an API to the platform:

<div className="py-4">
  <IconLink
    icon="service"
    href="/guides/how-to-sell-apis-on-ouro"
    title="How to monetize APIs"
    description="Charge for access to your API"
  />
</div>

## 2. Limiting access

When using Ouro as an API middleman, it's important to ensure that your service only responds to legitimate requests forwarded by Ouro.
This prevents unauthorized direct access to your API and maintains the integrity of your authentication and monetization setup.

### Domain whitelisting

Configure your API to accept requests only from our domain.
This involves checking the origin of incoming requests and rejecting any that don't come from Ouro's whitelisted domains.

You can use CORS configurations to ensure that your API only responds to the following origins:

- `api.ouro.foundation`

<DomainWhitelistCodeSamples
  samples={[
    {
      lang: "python",
      source:
        '```python\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\n\n# List of allowed domains\nALLOWED_DOMAINS = ["api.ouro.foundation"]\n\n# CORS middleware setup\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=ALLOWED_DOMAINS,\n    allow_credentials=True,\n    allow_methods=["*"],\n    allow_headers=["*"],\n)\n\n# Your API routes go here\n@app.get("/")\nasync def root():\n    return {"message": "Hello from your API!"}\n```',
    },
    {
      lang: "javascript",
      source:
        "```javascript\nconst express = require('express');\nconst cors = require('cors');\n\nconst app = express();\n\n// List of allowed domains\nconst ALLOWED_DOMAINS = ['api.ouro.foundation'];\n\n// CORS middleware setup\napp.use(cors({\n  origin: function (origin, callback) {\n    if (!origin || ALLOWED_DOMAINS.includes(origin)) {\n      callback(null, true);\n    } else {\n      callback(new Error('Not allowed by CORS'));\n    }\n  },\n  credentials: true\n}));\n\n// Your API routes go here\napp.get('/', (req, res) => {\n  res.json({ message: 'Hello from your API!' });\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => console.log(`Server running on port ${PORT}`));\n```",
    },
  ]}
/>

### Auth header verification

When you choose Ouro authentication for a Service, the platform issues a secret token tied to that Service. Your API should verify that requests include `Authorization: Basic <token>` and reject anything else. Store the token as an environment variable (e.g., `OURO_SERVICE_SECRET`).

FastAPI example:

```python showLineNumbers
from fastapi import FastAPI, Header, HTTPException, Depends, Request
import os
import time
import logging

app = FastAPI()

async def validate_ouro_authentication(
    authorization: str = Header(None, alias="Authorization"),
    request: Request = None,
):
    """Validate Ouro platform authentication using `Authorization: Basic <token>` header"""

    if not authorization or not authorization.lower().startswith("basic "):
        client_host = getattr(getattr(request, "client", None), "host", "unknown")
        logging.warning(f"Missing or invalid Authorization header from {client_host}")
        raise HTTPException(status_code=401, detail="Missing Ouro auth header")

    token = authorization.split(" ", 1)[1].strip()

    expected_secret = os.environ.get("OURO_SERVICE_SECRET")
    if not expected_secret:
        logging.error("Missing env var OURO_SERVICE_SECRET for Ouro authentication")
        raise HTTPException(status_code=500, detail="Server configuration error")

    if token != expected_secret:
        logging.warning("Invalid Ouro token")
        raise HTTPException(status_code=401, detail="Invalid Ouro credentials")

    return {"platform": "ouro", "authenticated_at": time.time()}

@app.post("/ouro/example")
async def ouro_only_endpoint(auth: dict = Depends(validate_ouro_authentication)):
    return {"ok": True, "via": auth["platform"]}
```

For a complete working example deployed on Modal, see the [Ouro as API middleware](/guides/deploying-to-modal) guide. Also see the high‑level concept overview: [Services on Ouro](/docs/concepts/services).
