Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

16.3 KB
Raw Blame
---
title: LobeHub API Authentication, Workspaces, and Scopes
description: >-
  Authenticate LobeHub public API calls with an API key or an OIDC access token
  obtained with PKCE, select a Workspace, and choose API key scopes.
tags:
  - LobeHub
  - REST API
  - Authentication
  - OIDC
  - PKCE
  - API Key
---

# LobeHub API Authentication, Workspaces, and Scopes

Every `/api/v1` request except `GET /api/v1/health`, `/api/v1/openapi.json`, and `/api/v1/docs` must carry a bearer token:

```http
Authorization: Bearer <token>
```

The server decides what kind of token it is by its shape:

- A token in the API key format (`sk-lh-` plus 58 lowercase letters and digits, or 16 for keys created earlier) is looked up as an **API key**. The key must be enabled and not expired.
- Any other token is validated as an **OIDC access token** (an RS256 JWT for the audience `urn:lobehub:chat`), signed by the deployment's OIDC provider. Self-hosted instances accept OIDC tokens only when `JWKS_KEY` is configured.

There is no `X-API-Key` header. A missing or invalid token returns `401` with a challenge that says where to authenticate:

```http
WWW-Authenticate: Bearer realm="LobeHub API", resource_metadata="https://app.lobehub.com/.well-known/oauth-protected-resource/api/v1"
```

That URL is the API's [RFC 9728](https://www.rfc-editor.org/rfc/rfc9728) protected resource metadata: the resource (`<origin>/api/v1`), its authorization server (`<origin>/oidc`, when OIDC is enabled) and the bearer method. The authorization server's [RFC 8414](https://www.rfc-editor.org/rfc/rfc8414) metadata is at `<origin>/.well-known/oauth-authorization-server/oidc`, the same document as the OIDC discovery below.

## Choose a Credential

| You are building                                                | Use                                                                                                                     |
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| A server-side integration, script, or CI job acting as yourself | An API key with the narrowest scopes that work                                                                          |
| A native or desktop app where each user signs in                | OIDC authorization code with PKCE, with a public client the deployment provides (see [OIDC with PKCE](#oidc-with-pkce)) |
| A third-party web app that users authorize                      | An OAuth app registered in Settings: client secret plus PKCE (see below)                                                |
| A command-line tool on a device without a browser               | The OIDC device flow (used by the built-in `lobehub-cli` client)                                                        |

## API Keys

Create keys in **Settings → API Keys** of a Workspace (`/<workspace>/settings/apikey`). A key belongs to the person who created it and to that Workspace.

- What a key can do is the **intersection** of its creator's own permissions (Workspace role and RBAC) and the key's scopes. Scopes only narrow access; they never grant more than the creator has.
- The creator can change a key's scopes later on its detail page (**Edit permissions**). Workspace admins can revoke other members' keys but cannot change their scopes.
- A key created before scopes existed, or created with **Full access**, has every scope.

## OIDC with PKCE

LobeHub runs an OpenID Connect provider at `<origin>/oidc`.

| Endpoint             | Path                                     |
| -------------------- | ---------------------------------------- |
| Discovery            | `/oidc/.well-known/openid-configuration` |
| Authorization        | `/oidc/auth`                             |
| Token                | `/oidc/token`                            |
| User info            | `/oidc/me`                               |
| JWKS                 | `/oidc/jwks`                             |
| Device authorization | `/oidc/device/auth`                      |
| Revocation           | `/oidc/token/revocation`                 |

PKCE is required for every authorization code request. Use `code_challenge_method=S256`.

Which client you can use:

- **LobeHub's own apps** use built-in public clients (`lobehub-desktop`, `lobehub-mobile`, and others). A public client has no secret, so the token request below sends only `client_id`.
- **Your own app on LobeHub Cloud** registers a web OAuth app in Settings (see [OAuth Apps](#oauth-apps)). It is a confidential client: add `client_secret` to the token request, and use an `https` or loopback `http` redirect URI. Custom URL schemes such as `myapp://` are not accepted for self-registered apps today.
- **Public clients for third-party native apps** become possible with dynamic client registration (`token_endpoint_auth_method: none`), which is coming soon in [#23322](https://github.com/lobehub/lobehub/pull/23322).

### Authorization Code Flow

1. Create a random `code_verifier` and its S256 `code_challenge` (base64url of the SHA-256 digest).

2. Open the authorization URL in the system browser:

   ```text
   https://app.lobehub.com/oidc/auth
     ?response_type=code
     &client_id=<client id>
     &redirect_uri=<registered redirect uri>
     &scope=openid profile email offline_access
     &resource=urn:lobehub:chat
     &code_challenge=<code_challenge>
     &code_challenge_method=S256
     &prompt=consent
     &state=<random state>
   ```

   `resource=urn:lobehub:chat` asks for an access token that `/api/v1` accepts. `offline_access` with `prompt=consent` returns a refresh token.

3. After sign-in, LobeHub redirects to `redirect_uri` with `code` and `state`. Reject the callback if `state` does not match.

4. Exchange the code:

   ```bash
   curl https://app.lobehub.com/oidc/token \
     -d grant_type=authorization_code \
     -d client_id=<client id> \
     -d code=<code> \
     -d redirect_uri=<redirect uri> \
     -d code_verifier=<code_verifier>
   # confidential clients (a web OAuth app) also send:
   #  -d client_secret=<client secret>
   ```

5. Call the API with `Authorization: Bearer <access_token>`. Refresh with `grant_type=refresh_token` before it expires.

Refresh tokens rotate: every refresh returns a new refresh token and the old one stops working, so always store the latest. Refresh tokens and sessions last 30 days.

The TypeScript SDK implements these steps as `createPkcePair`, `createAuthorizationUrl`, `parseAuthorizationCallback`, `exchangeAuthorizationCode`, and `refreshAccessToken` for public clients; they do not send a client secret. See [SDKs](/docs/development/api/sdks#sign-in-with-oidc-and-pkce).

### OAuth Apps

To let other people authorize your application, register it in **Settings → OAuth Apps** (`/<workspace>/settings/oauth-apps`):

- A web app gets a client id `lca_…` and a client secret `lcs_…`, shown once. It uses the `authorization_code` and `refresh_token` grants with `client_secret_post`.
- A device app is a public client that uses the device flow.
- Redirect URIs must use `https`, or `http` on a loopback address. Wildcards are not allowed, and an app can have at most 20.

Today an OAuth access token is a full user token: it reaches the same API as its user, without scope narrowing.

<Callout type="info">
  **Coming soon** ([#23322](https://github.com/lobehub/lobehub/pull/23322)): fine-grained API scopes
  for OAuth tokens (the same names as API key scopes, shown on the consent page), dynamic client
  registration at `POST /oidc/reg` with a single-use registration token, and the
  `client_credentials` grant for server-to-server apps. Each is turned on per deployment with an
  environment variable.
</Callout>

## Workspace Selection

Requests run in either the caller's personal space or one Workspace. The Workspace is resolved from the credential and the optional `X-Workspace-Id` header:

| Credential        | `X-Workspace-Id`                      | Result                                                                                           |
| ----------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Workspace API key | Not sent                              | Runs in the key's Workspace                                                                      |
| Workspace API key | Same Workspace                        | Runs in the key's Workspace                                                                      |
| Workspace API key | Different Workspace                   | `403` `Workspace API Key cannot access a different workspace`                                    |
| Personal API key  | Sent                                  | `403` `Personal API Key cannot access workspace data`                                            |
| OIDC token        | Sent                                  | Runs in that Workspace if the user is a member, otherwise `403` `Not a member of this workspace` |
| OIDC token        | Unknown Workspace id                  | `404` `Workspace not found`                                                                      |
| Workspace API key | Its Workspace does not allow API keys | `403` `Workspace API Key access is not available`                                                |

Inside a Workspace, some operations also need a minimum Workspace role (`viewer` \< `member` \< `admin` \< `owner`). A request below it returns `403` `Requires <role> role or higher`.

## Scopes

Scopes are defined in [`packages/const/src/apiKeyScope.ts`](https://github.com/lobehub/lobehub/blob/canary/packages/const/src/apiKeyScope.ts). A `:write` scope also grants the matching `:read` scope.

### Available Scopes

| Scope                                | Grants                                                                                                              |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| `*`                                  | Full access: everything the creator can do, except the explicit-only scopes listed below once they ship             |
| `agent:read` / `agent:write`         | Agents, Agent groups, tasks, goals, plugins, skills                                                                 |
| `agent:credential:write`             | Setting a password, token, or signing key on an Agent account (needs `agent:write` as well)                         |
| `chat:read` / `chat:write`           | Topics, messages, threads, sessions, translations                                                                   |
| `model:invoke`                       | Calling models: `POST /responses`, chat, image, video, speech, transcription. This is the scope that spends credits |
| `model:read` / `model:write`         | Providers and model configuration                                                                                   |
| `file:read` / `file:write`           | Files, uploads, parsing, and chunks                                                                                 |
| `knowledge:read` / `knowledge:write` | Libraries (knowledge bases), documents, chunks                                                                      |
| `mcp:read` / `mcp:write`             | MCP server configuration                                                                                            |
| `eval:read` / `eval:write`           | Evaluations, Benchmarks, Datasets, Test Cases                                                                       |
| `usage:read`                         | Usage and credit quota                                                                                              |
| `workspace:read` / `workspace:write` | Workspace details, members, audit log                                                                               |
| `user:read` / `user:write`           | The user profile, settings, Memory, notifications                                                                   |

Some operations need several scopes. For example `POST /responses` needs `model:invoke`, `chat:write`, and `agent:write`, because it runs an Agent and writes the conversation.

Restricted keys can never reach API key management, roles and RBAC administration, or billing, whatever scopes they hold.

A scope check failure returns `403`. Once unified error codes ship, the code is `insufficient_scope`; see [Errors](/docs/development/api/conventions#error-codes).

### Coming Soon Scopes

These scopes are added by open pull requests together with the endpoints that need them:

| Scope                                                                                                                                         | Endpoints                                                   | Pull request                                            |
| --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------- |
| `run:read` / `run:write`                                                                                                                      | `/runs` (Agent runs, events, cancel, steer, approvals)      | [#23253](https://github.com/lobehub/lobehub/pull/23253) |
| `webhook:read` / `webhook:write`                                                                                                              | `/webhooks`                                                 | [#23272](https://github.com/lobehub/lobehub/pull/23272) |
| `document:read` / `document:write`                                                                                                            | `/documents`, `/notebooks`                                  | [#23255](https://github.com/lobehub/lobehub/pull/23255) |
| `generation:read` / `generation:write`                                                                                                        | `/images`, `/videos`, `/generations`, `/audio`              | [#23267](https://github.com/lobehub/lobehub/pull/23267) |
| `tool:invoke`                                                                                                                                 | `POST /tools/call`                                          | [#23274](https://github.com/lobehub/lobehub/pull/23274) |
| `agent:transfer`                                                                                                                              | Moving an Agent to another Workspace or member              | [#23292](https://github.com/lobehub/lobehub/pull/23292) |
| `share:read` / `share:write`                                                                                                                  | Public share links                                          | [#23301](https://github.com/lobehub/lobehub/pull/23301) |
| `project:read` / `project:write`, `widget:read` / `widget:write` / `widget:publish`, `dashboard:read` / `dashboard:write`, `artifact:publish` | `/projects`, `/widgets`, `/dashboards`, artifact publishing | [#23311](https://github.com/lobehub/lobehub/pull/23311) |
| `oauth_app:read` / `oauth_app:write`, `trash:read` / `trash:write`                                                                            | `/oauth-apps`, `/trash`                                     | [#23315](https://github.com/lobehub/lobehub/pull/23315) |
| `device:read` / `device:operate`                                                                                                              | `/devices`, sandboxes                                       | [#23316](https://github.com/lobehub/lobehub/pull/23316) |
| `bot:read` / `bot:write`                                                                                                                      | `/bots`                                                     | [#23332](https://github.com/lobehub/lobehub/pull/23332) |

`device:operate` is planned as an **explicit** scope: full access does not include it, and it must be ticked by name when the key is created.

After [#23246](https://github.com/lobehub/lobehub/pull/23246) ships, each operation in the OpenAPI spec lists the scopes it needs under `x-required-scopes`, and the SDK shows them in each method's documentation.