# How to Set Up API Key Authentication for the OpenSandbox Server

> Secure your OpenSandbox server's Lifecycle API using API key authentication. Learn how to set up header validation and configure secrets for robust security.

- Repository: [Alibaba/OpenSandbox](https://github.com/alibaba/OpenSandbox)
- Tags: how-to-guide
- Published: 2026-03-08

---

**OpenSandbox secures its Lifecycle API through a FastAPI middleware that validates the `OPEN-SANDBOX-API‑KEY` request header against a secret configured in `~/.sandbox.toml`, returning 401 errors for missing or invalid credentials while exempting health checks and documentation endpoints.**

OpenSandbox implements API key authentication to protect its sandbox management endpoints. The system uses a pluggable `AuthMiddleware` class that integrates with the FastAPI application lifecycle to intercept requests before they reach route handlers. This guide covers the complete configuration and usage based on the actual implementation in the alibaba/OpenSandbox repository.

## Configure the API Key in ServerConfig

Authentication is controlled by the `api_key` field inside the server configuration section. In [`src/config.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/config.py), the `ServerConfig` dataclass defines this field at lines 80-84, which is parsed from a TOML configuration file.

Create or edit `~/.sandbox.toml` (the default path, overridable via the `SANDBOX_CONFIG_PATH` environment variable):

```toml
[server]
host = "0.0.0.0"
port = 8080
log_level = "INFO"

# Enable API key authentication

api_key = "my-secret-12345"

```

The `api_key` value can be any opaque string. For production deployments, inject this value via environment variables or a secrets manager rather than committing it to version control.

## How AuthMiddleware Enforces Authentication

The `AuthMiddleware` class in [`src/middleware/auth.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/middleware/auth.py) implements the actual security checks. When the FastAPI application starts in [`src/main.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/main.py) (lines 35-38), the middleware is registered via `app.add_middleware(AuthMiddleware, config=app_config)`.

During initialization, the middleware calls `_load_api_keys()` to extract the key from the `AppConfig` object. For every incoming request, the `dispatch` method performs the following logic:

1. **Path exemption check**: Requests to `/health`, `/docs`, `/redoc`, [`/openapi.json`](https://github.com/alibaba/OpenSandbox/blob/main//openapi.json), and proxy routes matching `/sandboxes/{id}/proxy/{port}/…` bypass authentication entirely.
2. **Configuration check**: If `self.valid_api_keys` is empty (no key configured), the middleware allows all requests.
3. **Header validation**: The middleware looks for the `OPEN-SANDBOX-API-KEY` header.
   - Missing header → Returns **401 Unauthorized** with code `MISSING_API_KEY`.
   - Invalid key → Returns **401 Unauthorized** with code `INVALID_API_KEY`.
   - Valid key → Proceeds to the route handler.

Error responses follow the standard schema defined in [`src/main.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/main.py), returning JSON objects with `code` and `message` fields.

## Starting the Server with Authentication

After configuring the TOML file, start the server from the repository root:

```bash
cd server
uv run python -m src.main

# Alternative: uvicorn src.main:app --host 0.0.0.0 --port 8080

```

The startup sequence loads the configuration via `load_config()`, initializes `AuthMiddleware` with the extracted secret, and mounts the middleware onto the FastAPI app. The server will now reject unauthenticated requests to protected endpoints.

## Making Authenticated API Requests

Clients must include the `OPEN-SANDBOX-API-KEY` header in all requests to protected endpoints. For example, to list sandboxes:

```bash
curl -H "OPEN-SANDBOX-API-KEY: my-secret-12345" \
     http://localhost:8080/v1/sandboxes

```

If authentication fails, the server returns structured error responses:

```json
{
  "code": "MISSING_API_KEY",
  "message": "Authentication credentials are missing. Provide API key via OPEN-SANDBOX-API-KEY header."
}

```

Or for incorrect values:

```json
{
  "code": "INVALID_API_KEY",
  "message": "Authentication credentials are invalid. Check your API key and try again."
}

```

## Bypassing Authentication for Local Development

To disable authentication for local testing, either omit the `api_key` field or set it to an empty string in `~/.sandbox.toml`:

```toml
[server]
api_key = ""

```

When `AuthMiddleware` detects an empty `valid_api_keys` set during initialization, it skips all header checks and allows unrestricted access. This is useful for development environments where credential management is unnecessary.

## Summary

- **Configuration**: Set `server.api_key` in `~/.sandbox.toml` (parsed by [`src/config.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/config.py)) to define the required secret.
- **Middleware**: `AuthMiddleware` in [`src/middleware/auth.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/middleware/auth.py) enforces checks on every request except exempt paths like `/health` and `/docs`.
- **Registration**: The middleware attaches to the FastAPI app in [`src/main.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/main.py) via `app.add_middleware()`.
- **Client Usage**: Send the key in the `OPEN-SANDBOX-API-KEY` header; missing or invalid keys trigger 401 responses with specific error codes.
- **Local Testing**: Leave `api_key` empty to bypass authentication entirely.

## Frequently Asked Questions

### What file paths does the authentication middleware ignore?

The `AuthMiddleware` in [`src/middleware/auth.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/middleware/auth.py) maintains an internal list of exempt paths including `/health`, `/docs`, `/redoc`, and [`/openapi.json`](https://github.com/alibaba/OpenSandbox/blob/main//openapi.json). Additionally, proxy routes matching `/sandboxes/{id}/proxy/{port}/…` are exempt to prevent accidental credential leakage through proxied connections.

### Can I configure multiple valid API keys for the OpenSandbox server?

The current implementation in [`src/middleware/auth.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/middleware/auth.py) supports a single API key via `ServerConfig.api_key`. However, the middleware stores keys in a set (`self.valid_api_keys`), suggesting the underlying structure could be extended to support multiple secrets if the configuration parsing logic in [`src/config.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/config.py) were modified to accept a list.

### Why am I getting a 401 error when accessing the Swagger UI?

If you configured an API key but receive `MISSING_API_KEY` when visiting `/docs`, verify that the Swagger documentation endpoint is not in your exemption list. By default, `/docs`, `/redoc`, and [`/openapi.json`](https://github.com/alibaba/OpenSandbox/blob/main//openapi.json) are exempt from authentication. If these are protected in your deployment, you must add the `OPEN-SANDBOX-API-KEY` header to your browser requests or configure your reverse proxy to inject it.

### How does the server handle API key validation errors?

When the `AuthMiddleware.dispatch` method detects a missing or invalid header, it returns a 401 Unauthorized response with a JSON body containing an error `code` field (`MISSING_API_KEY` or `INVALID_API_KEY`) and a descriptive `message`. This schema is consistent with the global error handling defined in [`src/main.py`](https://github.com/alibaba/OpenSandbox/blob/main/src/main.py).