> 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/api/preparation/authentication.md).

# API 認證

本篇將介紹在使用 MaiAgent API 時的身分驗證方法及取得方式

MaiAgent 使用 API 金鑰進行身分驗證。

## 身分認證方式

所有 API 請求必須在 HTTP Header 中包含 API Key，格式如下：

```javascript
const headers = {
  "Authorization": "Api-Key YOUR_API_KEY_HERE",
  "Content-Type": "application/json"
}
```

標頭的前綴是 `Api-Key`，不是 `Bearer`。金鑰綁定哪位成員、權限怎麼算、什麼情況會失效等規則，見 [API 共通規範：認證](https://docs.maiagent.ai/api/preparation/conventions.md#authentication)。

## 如何獲取 API 金鑰？

API 金鑰有兩種取得方式，兩種金鑰的呼叫方式相同：

* **成員自建**：組織內的有效成員都可以在後台右上角頭像 → <mark style="color:blue;">帳號</mark> → <mark style="color:blue;">API 金鑰</mark> 為自己建立金鑰，不需要額外權限。
* **管理者代發**：具備「API Key 管理權限」的管理者，可以在 <mark style="color:blue;">組織設定</mark> → <mark style="color:blue;">API Key 管理</mark> 替指定成員簽發金鑰，並設定到期時間與每分鐘請求數（RPM）。

操作步驟見使用者手冊 [API Key 管理](https://docs.maiagent.ai/org/developer/api-keys)：[成員自行建立金鑰](https://docs.maiagent.ai/org/developer/api-keys#self-issued-keys)、[管理者建立 API Key](https://docs.maiagent.ai/org/developer/api-keys#create-api-key)。

{% hint style="success" %}

* **安全提醒**：請妥善保管您的 API 金鑰，不要在公開場所分享
* **金鑰格式說明**：API 金鑰由前綴與密鑰兩段英數字組成，中間以 `.` 相連，呼叫時請完整帶入
  {% endhint %}

{% hint style="warning" %}
完整金鑰只會在建立成功時顯示一次。之後的列表僅顯示部分字元，無法再次查看或還原完整金鑰；若未保存，請建立新金鑰、更新使用該金鑰的服務，再撤銷舊金鑰。
{% endhint %}

## 找不到舊的系統簽發金鑰 <a href="#system-issued-api-key" id="system-issued-api-key"></a>

個人帳號的 <mark style="color:blue;">API 金鑰</mark>頁面只列出您自行建立的金鑰。首次加入組織（包含透過 AD 首次登入）時，系統可能會自動簽發一把無到期日的金鑰，但不會提供其完整值，因此無法取得該金鑰來呼叫 API。若要呼叫 API，請在個人頁面自行建立新金鑰，並在建立成功時立即保存完整值。

系統自動簽發或由管理者代為簽發的金鑰，只有具有組織金鑰管理權限的成員可從 <mark style="color:blue;">組織金鑰管理</mark>查看其擁有者、前綴、簽發來源、狀態與到期日，但該頁不會顯示完整值。若您沒有此權限，可請組織擁有者或具有組織金鑰管理權限的成員協助確認或撤銷舊金鑰。

## API 金鑰的權限範圍 <a href="#api-key-permissions" id="api-key-permissions"></a>

以 API 金鑰呼叫 API 時，權限與金鑰擁有者在該組織的角色權限相同；缺少所需權限時，API 會回傳 403 Forbidden。

成員（members）與角色（groups）的寫入操作都需要子權限 <mark style="color:blue;">組織概覽權限</mark>（位於 <mark style="color:blue;">組織權限</mark> 之下），組織擁有者則不受此限。適用的操作包含：

* 新增成員：`POST /api/v1/organizations/{organizationPk}/members/`
* 移除成員：`DELETE /api/v1/organizations/{organizationPk}/members/{id}/`
* 調整成員所屬角色：`POST /api/v1/organizations/{organizationPk}/members/{id}/update-groups/`
* 建立、更新、刪除角色：`POST` / `PUT` / `PATCH` / `DELETE /api/v1/organizations/{organizationPk}/groups/…`
* 批量新增或移除角色成員、分配或移除角色的 AI 助理、收件匣、知識庫與資料庫：`/api/v1/organizations/{organizationPk}/groups/{groupPk}/group-*/…`
* 其他成員與角色的寫入操作（例如批次匯入成員）同樣適用

{% hint style="info" %}
權限以子項判斷：角色設定中父層 <mark style="color:blue;">組織權限</mark> 未勾，不代表其下的 <mark style="color:blue;">組織概覽權限</mark> 未勾。排查 403 時，請到後台 <mark style="color:blue;">組織設定 → 角色</mark> 展開 <mark style="color:blue;">組織權限</mark>，確認金鑰擁有者所屬角色是否勾選 <mark style="color:blue;">組織概覽權限</mark>。
{% endhint %}

## 錯誤處理

當認證錯誤時，API 會回傳 401 Unauthorized 的 HTTP 錯誤代碼：

* **API Key 缺失、格式錯誤或無效**

沒帶金鑰、標頭格式不對，或金鑰無效（不存在、已到期、已停用、已撤銷，或綁定的成員已停用、已移出組織），都回同樣的內容，不會說明是哪一種原因：

```json
{
  "detail": "Authentication credentials were not provided."
}
```

*修復建議：檢查請求標頭是否為 `Authorization: Api-Key YOUR_API_KEY`，並確認 API Key 完整、沒有多餘的空格或字元。格式正確仍失敗時，請到 <mark style="color:blue;">API Key 管理</mark> 確認金鑰不是已停用、已過期或已撤銷，以及綁定的成員仍是啟用狀態。*

* **把 API Key 放在 `Bearer` 後面**

平台會把它當成登入權杖驗證，回應內容不同：

```json
{
  "detail": "Given token not valid for any token type",
  "code": "token_not_valid",
  "messages": [ … ]
}
```

*修復建議：把前綴改成 `Api-Key`。*

`401` 回應會帶 `WWW-Authenticate` 標頭，多數端點的值是 `Bearer realm="api"`，請以狀態碼判斷，不要依這個標頭決定要帶哪一種憑證，說明見 [API 共通規範：認證失敗的回應](https://docs.maiagent.ai/api/preparation/conventions.md#auth-errors)。金鑰有效但權限不足時回 `403`，見上方 [API 金鑰的權限範圍](#api-key-permissions)。


---

# 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/api/preparation/authentication.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.
