# Authentication & Scopes

> OpenGen authenticates REST and MCP requests using workspace-scoped API keys (og_sk_), OAuth 2.1 Dynamic Client Registration with S256 PKCE tokens (og_mcp_a_), or HttpOnly browser sessions. Provider API keys are never OpenGen client credentials; BYOK supplier keys are stored encrypted separately per deployment.

## Agent Prompt

```text
Verify workspace authentication before running private OpenGen endpoints using https://opengen.dev/docs/authentication:
1. Never accept or send a third-party provider key (such as an OpenAI or fal key) as an OpenGen Authorization Bearer token, and never place tokens in URLs or shell argv.
2. For public discovery (GET https://opengen.dev/v1/models, /v1/pricing, /openapi.json, or https://opengen.dev/mcp/readonly public tools), no token is needed.
3. For private reads (GET https://opengen.dev/v1/balance, /v1/analytics, /v1/generations, /v1/assets), confirm read scope. For paid submissions, uploads, cancellations, or deletions, confirm generate scope and verify budget via POST https://opengen.dev/v1/pricing/estimate before submitting with an Idempotency-Key.
4. When using OAuth on https://opengen.dev/mcp or https://opengen.dev/mcp/readonly, discover metadata at /.well-known/oauth-protected-resource/mcp (or /mcp/readonly) and /.well-known/oauth-authorization-server.
```

## Authentication methods

OpenGen supports three authentication transports, all strictly scoped to a single workspace:

| Method                      | Token or Cookie                                 | Intended Caller                                               | Lifecycle & Revocation                                                                                                                |
| --------------------------- | ----------------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Workspace API key           | `Authorization: Bearer og_sk_<64-hex>`          | Server backends, CI jobs, scripts, non-OAuth agents           | Created in `/app/keys`; supports explicit scopes, expiry, routing policy, and monthly spend cap; revocable anytime                    |
| OAuth 2.1 (DCR + S256 PKCE) | `Authorization: Bearer og_mcp_a_<43-base64url>` | Hosted assistants, coding agents, IDEs, `@opengen-dev/cli`    | 1-hour access token TTL; 30-day grant with refresh-token rotation (`og_mcp_r_...`); revocable via `POST /oauth/revoke` or `/app/apps` |
| Browser session cookie      | `Cookie: og_session=<opaque>`                   | OpenGen web console (`/dashboard`, `/playground`, `/billing`) | `HttpOnly`, `SameSite=Lax`, `Secure` on HTTPS, 12-hour TTL; signed in via Google OIDC, GitHub OAuth, or Email OTP                     |

> [!IMPORTANT]
> Upstream supplier keys (OpenAI, fal, Alibaba, BytePlus, Replicate, etc.) are **never** OpenGen authentication credentials. For Bring Your Own Key (`"billing": "byok"`), store encrypted supplier keys per regional deployment in `/app/providers`, then call OpenGen with your OpenGen workspace token.

## Scoped workspace API keys

Create dedicated least-privilege keys in `/app/keys`. Send the key strictly in the `Authorization` header — never in query strings, request bodies, committed files, or CLI positional arguments.

```bash tab="cURL"
# Verify authentication and inspect available/reserved workspace credit
curl --fail-with-body "$OPENGEN_API_URL/v1/balance" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"
```

```ts tab="TypeScript"
const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const res = await fetch(`${baseUrl}/v1/balance`, {
  headers: {
    Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`,
  },
});

if (res.status === 401) {
  throw new Error('OpenGen API key is missing, expired, or revoked.');
}
console.log(await res.json());
```

```python tab="Python"
import os
import httpx

base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
response = httpx.get(
    f"{base_url}/v1/balance",
    headers={"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"},
    timeout=15.0,
)
response.raise_for_status()
print(response.json())
```

```bash tab="CLI"
# Browser PKCE login (recommended for local interactive terminals)
opengen login

# Or authenticate headless CI via environment variable (overrides saved browser login)
export OPENGEN_API_KEY="og_sk_..."
opengen status
```

Each workspace API key can optionally bind:

- **Expiration (`expiresAt`)**: expired keys immediately fail with `401 unauthorized`.
- **Monthly spend cap (`monthlyCapMicros`)**: hard integer micro-USD ceiling per key.
- **Governance routing policy (`policyId`)**: restricts allowed models, serving providers, endpoint regions, and per-request `maxCostMicros`. Request-level `routing` parameters can only narrow an attached policy, never broaden it.

## Permission scopes

Every workspace credential carries an explicit set of scopes. Requests missing the required scope fail closed with `403 insufficient_scope`.

| Scope               | Public Developer Endpoints & MCP Tools                                                                                                                                                                                                                                                                        | Notes                                                                                                |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| _(none — public)_   | `GET /health`, `GET /openapi.json`, `GET /v1/models*`, `GET /v1/collections*`, `GET /v1/routes`, `GET /v1/pricing`, `POST /v1/pricing/estimate`, `GET /.well-known/webhook-jwks.json`, and 4 public tools on `/mcp/readonly`                                                                                  | Unauthenticated catalog GETs are CDN-cached; authenticated calls switch to `Cache-Control: no-store` |
| `read`              | `GET /v1/balance`, `GET /v1/analytics`, `GET /v1/generations`, `GET /v1/generations/lookup`, `GET /v1/generations/{id}`, `GET /v1/generations/{id}/status`, `GET /v1/generations/{id}/events`, `GET /v1/assets`, and workspace read MCP tools (`balance`, `analytics`, `job_get`, `jobs_list`, `assets_list`) | Safe read-only visibility into workspace balance, jobs, outputs, assets, and analytics               |
| `generate`          | `POST /v1/generations`, `POST /v1/generations/{id}/cancel`, `DELETE /v1/generations/{id}/outputs`, `POST /v1/assets`, `POST /v1/assets/complete`, `DELETE /v1/assets`, and `/mcp` write tools (`generate`, `job_cancel`, `upload_asset`, `upload_attachment`, `delete_asset`, `purge_job_outputs`)            | Authorizes spending managed credit or BYOK runs and mutating/purging private media                   |
| `keys:write`        | Workspace API key administration (internal console surface)                                                                                                                                                                                                                                                   | Never delegated via MCP OAuth                                                                        |
| `policies:write`    | Governance routing policy administration                                                                                                                                                                                                                                                                      | Never delegated via MCP OAuth                                                                        |
| `connections:write` | Encrypted BYOK provider connection administration                                                                                                                                                                                                                                                             | Never delegated via MCP OAuth                                                                        |
| `webhooks:write`    | Workspace alert configuration (`GET/PUT /v1/alerts/settings`, `GET /v1/alerts`)                                                                                                                                                                                                                               | Not required for per-request `webhookUrl` on `POST /v1/generations`                                  |
| `members:write`     | Team membership and role administration                                                                                                                                                                                                                                                                       | Admin only; never delegated via MCP OAuth                                                            |
| `feedback:write`    | Feedback and catalog request submission                                                                                                                                                                                                                                                                       | Never delegated via MCP OAuth                                                                        |

> [!NOTE]
> OAuth 2.1 grants for MCP and `@opengen-dev/cli` can only request `read` and `generate` (and `/mcp/readonly` grants are strictly restricted to `read`). Administrative `*:write` scopes are never delegated through OAuth.

## OAuth 2.1 with Dynamic Client Registration & PKCE

OpenGen implements OAuth 2.1 with Dynamic Client Registration (RFC 7591), S256 PKCE, Protected Resource Metadata (RFC 9728), and Resource Indicators (RFC 8707). OpenGen does not use Client ID Metadata Documents (CIMD).

### Discovery and protocol endpoints

- `GET /.well-known/oauth-authorization-server` — authorization server metadata (`issuer`, `authorization_endpoint`, `token_endpoint`, `registration_endpoint`, `revocation_endpoint`, `code_challenge_methods_supported: ["S256"]`, `token_endpoint_auth_methods_supported: ["none"]`).
- `GET /.well-known/oauth-protected-resource` and `GET /.well-known/oauth-protected-resource/mcp` — RFC 9728 metadata for full `/mcp` (`scopes_supported: ["read", "generate"]`).
- `GET /.well-known/oauth-protected-resource/mcp/readonly` — RFC 9728 metadata for `/mcp/readonly` (`scopes_supported: ["read"]`).
- `POST /oauth/register` — public client registration (`1–10` redirect URIs; supports public HTTPS callbacks, RFC 8252 literal HTTP loopback `http://127.0.0.1` / `http://[::1]` with ephemeral positive ports, and exact `http://localhost:<port>/` callbacks).
- `GET /oauth/authorize` — browser authorization endpoint requiring `response_type=code` and `code_challenge_method=S256`.
- `POST /oauth/token` — exchanges `authorization_code` or rotates `refresh_token` (`1` hour access token TTL, `30` day grant lifetime).
- `POST /oauth/revoke` — revokes an access or refresh token (grants can also be revoked individually in `/app/apps`).

### RFC 8707 audience isolation

OAuth tokens minted for `/mcp` (`resource: "https://opengen.dev/mcp"`) and tokens minted for `/mcp/readonly` (`resource: "https://opengen.dev/mcp/readonly"`) are strictly audience-isolated. Presenting a `/mcp/readonly` token to `/mcp` — or a `/mcp` token to `/mcp/readonly` — fails with `401` and a `WWW-Authenticate` challenge pointing to the matching `resource_metadata` URL.

## Workspace isolation, CSRF, and caching boundaries

- **Expected workspace guard**: On `GET /v1/balance`, callers can send `X-OpenGen-Expected-Workspace: <workspaceId>` to ensure the credential still resolves to the intended paying workspace; mismatches return `409 workspace_changed`.
- **CSRF protection**: Cookie-bearing (`og_session`) cross-origin mutations are rejected with `403 origin_denied`. Cookie-free Bearer/public cross-origin `POST` calls on `/mcp`, `/mcp/readonly`, and `/v1/pricing/estimate` are permitted via public CORS (`Access-Control-Allow-Origin: *`, never `Access-Control-Allow-Credentials: true`).
- **Private caching**: Every request carrying an `Authorization` header or `og_session` cookie — and every private endpoint under `/v1/generations*`, `/v1/assets*`, `/v1/balance`, `/v1/analytics`, `/mcp`, and `/mcp/readonly` — is served with `Cache-Control: no-store`.

## Related pages

- [MCP Server & Tools](/docs/mcp) — connect `/mcp` or zero-auth `/mcp/readonly`.
- [Agent Clients](/docs/clients) — client-specific OAuth setup for ChatGPT, Claude, Codex, Claude Code, Cursor, Grok Bot, Hermes Agent, Muse Code, and CLI.
- [Errors & Recovery](/docs/errors) — handle `401 unauthorized`, `403 insufficient_scope`, and `403 policy_denied`.
