> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/identity-and-access/maiagent-oauth-server.md).

# MaiAgent 作為 OAuth 授權伺服器

讓 Claude 等 MCP 客戶端以 OAuth 2.1（授權碼＋PKCE）連線 MaiAgent MCP：端點、應用程式註冊、Redirect URI、權杖效期與輪替，以及 scope 的實際作用

MaiAgent 內建 OAuth 2.1 授權伺服器。Claude 等 MCP 客戶端可以用 OAuth 連線 MaiAgent MCP，不必在設定檔裡貼 API Key：成員在瀏覽器登入、按下授權後，客戶端取得短效的存取權杖，以這位成員的身分操作 MaiAgent。本頁寫給兩種讀者：要讓員工在 MCP 客戶端用自己帳號連 MaiAgent 的客戶 IT，以及要讓自家服務以成員身分呼叫 MaiAgent 的開發者。

{% hint style="info" %}
**和使用者手冊的分工**：後台操作見使用者手冊[OAuth 應用程式](https://docs.maiagent.ai/org/developer/oauth-applications)；MCP 客戶端的連線設定（API Key 與 OAuth）見[MaiAgent MCP](/tech/mcp/maiagent-mcp.md)。本頁只寫協定規格與整合要點。
{% endhint %}

本頁說的是 MaiAgent **核發**權杖。反方向，也就是 MaiAgent 去連第三方 OAuth 服務，請見[OAuth 2.0 整合與 Token 自動刷新機制](/tech/advanced-genai-tech/oauth-integration.md)。

## OAuth 與 API Key 怎麼選 <a href="#oauth-or-api-key" id="oauth-or-api-key"></a>

| 項目         | OAuth（本頁）                                   | API Key                                                                          |
| ---------- | ------------------------------------------- | -------------------------------------------------------------------------------- |
| 代表的身分      | 按下授權的成員本人                                   | 金鑰綁定的成員                                                                          |
| 交付方式       | 成員在瀏覽器登入並同意，不必經手任何密鑰                        | 複製金鑰貼進客戶端設定                                                                      |
| 效期         | 存取權杖 1 小時，由客戶端自動換新                          | 依金鑰的到期時間，可設為永不過期                                                                 |
| 權限         | 等於成員角色，scope 不另外限制（見[scope 的實際作用](#scopes)） | 等於成員角色                                                                           |
| 金鑰的 RPM 限制 | 不適用                                         | 適用，見[API 共通規範](https://docs.maiagent.ai/api/preparation/conventions#rate-limits) |

只用 SSO 登入、沒有 MaiAgent 密碼的成員也可透過組織帳號完成 OAuth 授權，見[登入與同意](#login-and-consent)。

## 端點 <a href="#endpoints" id="endpoints"></a>

SaaS 的授權伺服器是 `https://api.maiagent.ai`。地端與私有雲部署請換成貴公司的平台網域，中繼資料裡的網址會跟著請求的網域產生。

| 用途                  | 方法與路徑                                         |
| ------------------- | --------------------------------------------- |
| 授權伺服器中繼資料（RFC 8414） | `GET /.well-known/oauth-authorization-server` |
| 授權                  | `GET /o/authorize/`                           |
| 換發權杖                | `POST /o/token/`                              |
| 撤銷權杖（RFC 7009）      | `POST /o/revoke_token/`                       |

中繼資料宣告的能力如下，和實際行為一致：

| 欄位                                      | 值                                                 |
| --------------------------------------- | ------------------------------------------------- |
| `response_types_supported`              | `code`                                            |
| `grant_types_supported`                 | `authorization_code`、`refresh_token`              |
| `code_challenge_methods_supported`      | `S256`                                            |
| `token_endpoint_auth_methods_supported` | `none`、`client_secret_basic`、`client_secret_post` |
| `scopes_supported`                      | `read`、`write`                                    |

{% hint style="warning" %}
MaiAgent **不支援動態用戶端註冊（Dynamic Client Registration）**，中繼資料沒有 `registration_endpoint`。MCP 客戶端必須能填入預先註冊的 Client ID，請先依下一節在組織裡註冊應用程式。
{% endhint %}

## 在組織註冊 OAuth 應用程式 <a href="#register-application" id="register-application"></a>

在後台 <mark style="color:blue;">組織設定</mark> → <mark style="color:blue;">組織概覽</mark> → <mark style="color:blue;">管理操作</mark> → <mark style="color:blue;">OAuth 應用程式</mark> 建立應用程式、取得 Client ID；頁面上的 <mark style="color:blue;">連線資訊</mark> 卡片列出 Discovery、Authorize 與 Token 端點。建立步驟、誰能管理、Client Secret 的保存與重新產生，見使用者手冊[OAuth 應用程式](https://docs.maiagent.ai/org/developer/oauth-applications)。整合時要注意：

* **應用程式類型建立後不可變更**：Public 給 MCP 客戶端（如 Claude），靠 PKCE 授權，不核發 client secret；Confidential 給伺服器端整合，會核發 client secret。
* 重新產生 Client Secret 後舊 secret 立即失效，已核發的權杖不受影響；刪除應用程式後，所有透過它連線的成員，權杖立即全部失效。
* 每個組織最多 20 個 OAuth 應用程式。
* 同一套功能也有 API：`/api/v1/oauth/applications/`（GET、POST、PATCH、DELETE，另有 `POST …/{id}/regenerate-secret/`），權限規則與後台相同。

## Redirect URI 規則 <a href="#redirect-uris" id="redirect-uris"></a>

* **完全比對**：scheme、主機、連接埠與路徑都要一致，不支援萬用字元；註冊的 URI 若帶查詢參數，授權請求也必須帶上。
* 只接受 `https://`。`http://` 只限本機回呼：`localhost`、`127.0.0.1`、`::1`。
* 本機回呼的連接埠：註冊 `http://127.0.0.1/…` 或 `http://[::1]/…` 時，授權請求可以使用任意連接埠（RFC 8252）；註冊 `http://localhost:<埠>/…` 時，連接埠必須完全相同。本機 MCP 客戶端每次隨機挑埠時，請註冊 `127.0.0.1` 的形式。
* 網頁版 MCP 客戶端的回呼網址以該客戶端的文件為準，後台表單的範例是 `https://claude.ai/api/mcp/auth_callback`。

## 授權流程 <a href="#authorization-flow" id="authorization-flow"></a>

MCP 客戶端連線 MaiAgent MCP（SaaS 為 `https://mcp.maiagent.ai/mcp`）時，整個流程如下：

1. 客戶端沒有帶憑證，MCP 伺服器回 `401`，`WWW-Authenticate` 標頭指向 `https://mcp.maiagent.ai/.well-known/oauth-protected-resource/mcp`。
2. 客戶端讀這份資源中繼資料（RFC 9728），`authorization_servers` 指向 `https://api.maiagent.ai`，再讀授權伺服器中繼資料。
3. 客戶端開瀏覽器到 `/o/authorize/`，成員登入並同意。
4. MaiAgent 把授權碼導回 Redirect URI，客戶端帶 `code_verifier` 到 `/o/token/` 換權杖。
5. 之後每次呼叫都帶 `Authorization: Bearer <access_token>`。存取權杖過期或被撤銷時，MCP 伺服器回 `401`，客戶端用更新權杖換新。

自行實作客戶端時，授權請求與換發請求的格式如下：

```http
GET /o/authorize/?response_type=code&client_id=<CLIENT_ID>&redirect_uri=<REDIRECT_URI>&code_challenge=<CODE_CHALLENGE>&code_challenge_method=S256&state=<STATE>
```

```bash
curl -X POST https://api.maiagent.ai/o/token/ \
  -d grant_type=authorization_code \
  -d code=<CODE> \
  -d redirect_uri=<REDIRECT_URI> \
  -d client_id=<CLIENT_ID> \
  -d code_verifier=<CODE_VERIFIER>
```

* **PKCE 一律必填**，Public 與 Confidential 都一樣，`code_challenge_method` 用 `S256`。
* Confidential 應用程式另外以 HTTP Basic（`client_secret_basic`）或表單欄位 `client_secret`（`client_secret_post`）帶 secret。
* 授權碼 300 秒內有效。
* 換發回應包含 `access_token`、`token_type`（`Bearer`）、`expires_in`（`3600`）、`refresh_token` 與 `scope`。

### 登入與同意 <a href="#login-and-consent" id="login-and-consent"></a>

* 授權頁保留 Email 與密碼登入；續行授權時，也提供 <mark style="color:blue;">以組織帳號（SSO）登入</mark>。這個入口交由後台完成登入，再回到授權頁，因此只用 SSO、沒有 MaiAgent 密碼的成員也能授權。
* 同意頁會顯示應用程式名稱、所屬組織，以及成員目前登入的 Email。
* 成員已經有這個應用程式的有效權杖時，重新連線會略過同意頁。

### SSO 登入交接與安全邊界 <a href="#sso-login-handoff" id="sso-login-handoff"></a>

例如，企業員工平常用 SAML 登入 MaiAgent，沒有另外設定 MaiAgent 密碼。當 Claude 等 MCP 客戶端開啟授權頁時，員工選擇組織帳號登入，完成平常的後台登入後返回授權頁，再同意讓客戶端以自己的身分連線。

SSO 交接是瀏覽器登入流程，不取代客戶端原本的授權碼與 PKCE 交換：客戶端仍使用上方的授權與權杖端點，無須自行處理後台登入交接碼。整合端需注意：

* 後台收到的簽章登入請求有效 10 分鐘；完成登入後使用的一次性交接碼有效 300 秒，只能兌換一次。這個交接碼與 MCP 客戶端取得的 OAuth 授權碼用途不同。
* 交接碼綁定發起登入的瀏覽器，且只會續行本站的 `/o/authorize/`；不能拿到另一個瀏覽器使用，也不能指定外站作為登入後的回跳位置。
* 帳號被停用，或其 SSO 認證來源關閉登入時，無法完成交接。成員主動登出後，登出前尚未完成的登入嘗試也會失效。
* API Key 與成員嵌入式 token 不能換取登入交接碼。它們不能用來代替成員在瀏覽器完成登入與授權。

{% hint style="warning" %}
登入交接未完成、逾時或失效時，請從授權登入頁重新開始，不要重送舊交接碼。
{% endhint %}

### 權杖代表誰、屬於哪個組織 <a href="#token-identity" id="token-identity"></a>

* 權杖代表按下授權的成員，組織固定為**應用程式所屬的組織**，呼叫時不需要也不靠 `X-Organization-Id` 標頭。
* 呼叫當下，這位成員必須是該組織的有效成員。成員被停用、移出組織，或組織被刪除後，權杖立即無法使用，API 回 `401`。
* 存取權杖也能直接呼叫平台 REST API（`Authorization: Bearer <access_token>`），權限判斷和 API Key 相同。例外：AI Gateway 的 OpenAI 相容端點只接受 API Key；刪除自己的帳號這類高風險操作只接受互動登入。

## 權杖效期與輪替 <a href="#token-lifetime" id="token-lifetime"></a>

| 項目      | 規則                                                                 |
| ------- | ------------------------------------------------------------------ |
| 授權碼     | 300 秒                                                              |
| 存取權杖    | 3600 秒（1 小時）                                                       |
| 更新權杖    | 每次使用都會輪替：回應帶一把新的更新權杖，舊的隨即作廢                                        |
| 輪替後重送   | 同一個請求因網路或併發而重送時，剛被輪替的舊更新權杖在 120 秒內仍可使用                             |
| 明確撤銷    | 立即生效，沒有 120 秒寬限                                                    |
| 更新權杖的效期 | 每把更新權杖自核發起 30 天有效；每次成功換發都會輪替為新權杖，並從新權杖的核發時間重新計算 30 天。逾期未換發時，需要重新授權 |

整合端收到 `invalid_grant` 時，請停止使用這把更新權杖，引導成員重新授權，不要在背景重試。撤銷與輪替的細節見[更新權杖被撤銷或失效時](#refresh-token-revocation)。

撤銷的方式有三種：

| 誰來撤銷  | 做法                                                                                                                | 影響範圍            |
| ----- | ----------------------------------------------------------------------------------------------------------------- | --------------- |
| 整合端   | `POST /o/revoke_token/`，帶 `token`（可加 `token_type_hint`）與 client 認證                                                | 單一權杖            |
| 成員本人  | `GET /api/v1/oauth/authorized-applications/` 列出自己授權過的應用程式，`DELETE /api/v1/oauth/authorized-applications/{id}/` 撤銷 | 這位成員給該應用程式的所有權杖 |
| 組織管理者 | 刪除 OAuth 應用程式                                                                                                     | 所有成員給該應用程式的所有權杖 |

### 更新權杖被撤銷或失效時 <a href="#refresh-token-revocation" id="refresh-token-revocation"></a>

更新權杖被明確撤銷後，立即不能再換取存取權杖。整合端若繼續拿它向 `POST /o/token/` 換發，會收到 HTTP 400，錯誤碼為 `invalid_grant`。整合端請這樣處理：

1. 收到 `invalid_grant` 時，停止使用這把更新權杖，引導成員重新授權，不要在背景重試。
2. 成員撤銷整個已授權的應用程式時，這位成員給該應用程式的所有權杖都會被撤銷，舊的更新權杖全部不能再用。
3. 正常輪替後，同一個請求因網路或併發而重送時，剛被輪替的舊更新權杖有 120 秒的重試寬限；這段寬限不適用於明確撤銷。

{% hint style="warning" %}
請把 `invalid_grant` 視為需要重新授權的訊號：不要假設明確撤銷後還有 120 秒可用。30 天效期是上限，不保證權杖在期限內一定可用；撤銷、應用程式被刪除或成員被停用仍可能讓授權提前失效。
{% endhint %}

## scope 的實際作用 <a href="#scopes" id="scopes"></a>

授權伺服器接受 `read` 與 `write` 兩個 scope；授權請求沒帶 `scope` 時，預設兩個都給。**scope 目前不會限制任何 API**：能做什麼完全由成員的角色權限決定，和這位成員登入後台或使用 API Key 時相同。要限制 MCP 客戶端能做的事，請替它的使用者設計專用角色，見使用者手冊[角色權限管理](https://docs.maiagent.ai/org/roles/role-permission)。

## 常見問題 <a href="#faq" id="faq"></a>

<details>

<summary>MCP 客戶端顯示找不到註冊端點或無法註冊？</summary>

MaiAgent 不支援動態用戶端註冊。請先在 <mark style="color:blue;">OAuth 應用程式</mark> 建立應用程式，再把 Client ID（Confidential 另加 Client Secret）填進 MCP 客戶端的 OAuth 設定。

</details>

<details>

<summary>授權時出現 redirect_uri 不符？</summary>

Redirect URI 採完全比對。請確認 scheme、主機、連接埠、路徑和註冊值一字不差；本機客戶端若每次換埠，請改註冊 `http://127.0.0.1/…` 的形式。

</details>

<details>

<summary>連線一陣子之後要求重新授權？</summary>

更新權杖自核發起超過 30 天未換發，或已被撤銷時，權杖端點回 `invalid_grant`，客戶端只能請成員重新授權。成員被停用後，以存取權杖呼叫 API 會被拒（HTTP 401）。重新產生 client secret 不會讓已核發的權杖失效。

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/identity-and-access/maiagent-oauth-server.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
