> 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/conversations/web-chat/source-id-access.md).

# 以聯絡人 Source ID 免登入對話

讓您網站上已登入的使用者帶著自己的使用者編號（Source ID）直接對話，不必再登入一次。平台會依此編號對應到一位聯絡人，未經您後端簽章的請求則無法冒用任何人的身分。

把 Web Chat 嵌入自家網站時，使用者往往已經在您的網站登入過。這個設定讓他們帶著您系統的使用者編號直接開始對話，不必再經過一次登入畫面；同時公開對話網址仍然擋掉匿名訪問。

這個編號在 MaiAgent 稱為 **Source ID**，後台畫面與嵌入腳本都用這個名稱。平台收到 Source ID 後，會對應到（或建立）一位**聯絡人**，該使用者的對話紀錄就掛在這位聯絡人身上。

## <mark style="color:blue;">一、這個設定解決什麼問題</mark> <a href="#what-it-solves" id="what-it-solves"></a>

在此設定之前，登入設定是二選一：

* 開啟登入設定：嵌入端明明已經驗證過身分，使用者仍被要求再登入一次。
* 關閉登入設定：公開對話網址任何人都能匿名使用。

開啟本設定後，兩者可以同時成立：帶著 Source ID 與有效簽章進來的使用者直接對話，沒帶的訪問一律導向登入頁。

{% hint style="info" %}
本設定預設關閉。關閉時，所有既有行為完全不變。
{% endhint %}

## <mark style="color:blue;">二、開啟設定</mark> <a href="#enable" id="enable"></a>

設定位置：左側選單 「 <mark style="color:blue;">客服對話 > 對話平台</mark> 」，選擇一個網站類型的對話平台，進入 「 <mark style="color:blue;">登入設定</mark> 」 分頁。

### 1. 先選擇登入來源 <a href="#prerequisite" id="prerequisite"></a>

本開關依附於登入設定，必須先在 「 <mark style="color:blue;">登入來源</mark> 」 選定一種來源（MaiAgent／AD／Keycloak／LINE）。尚未選擇時開關無法點選，畫面會顯示 「 <mark style="color:blue;">請先選擇登入來源</mark> 」。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-0bed4d025474ad42bf838b7e9e00e78f90693425%2Fsourceid-01-default.png?alt=media" alt=""><figcaption><p>登入設定分頁，本開關預設關閉</p></figcaption></figure>

### 2. 開啟開關 <a href="#toggle" id="toggle"></a>

開啟 「 <mark style="color:blue;">允許嵌入端以 Source ID 免登入對話</mark> 」。開啟後才會出現驗證方式、簽章密鑰與整合範例。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-95e715c203b5b89846e419419586baad4076301b%2Fsourceid-02-enabled-signature.png?alt=media" alt=""><figcaption><p>開啟後展開的設定區塊，驗證方式預設為「要求簽章驗證」</p></figcaption></figure>

### 3. 選擇驗證方式 <a href="#verify-mode" id="verify-mode"></a>

| 驗證方式                                          | 說明                                            | 適用情境      |
| --------------------------------------------- | --------------------------------------------- | --------- |
| <mark style="color:blue;">要求簽章驗證</mark>（建議）   | 嵌入端須附上由您後端計算的簽章，驗章通過才放行。只有持有密鑰的伺服器能代表使用者發起對話。 | 正式環境      |
| <mark style="color:blue;">僅憑 Source ID</mark> | 不驗簽章，帶了 Source ID 就放行。                        | 測試或內網封閉環境 |

{% hint style="danger" %}
選擇 「僅憑 Source ID」 時，Source ID 就等於通行證。若您的 Source ID 是 email、學號、員工編號等可猜測的值，他人可冒用該身分對話並讀取其歷史紀錄。需要身分保證的場景請使用簽章模式，或改用 AD／Keycloak／MaiAgent 登入。
{% endhint %}

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-8fa84f2e4965e66f8872be1997424f02b47e77c5%2Fsourceid-03-raw-mode-warning.png?alt=media" alt=""><figcaption><p>選擇「僅憑 Source ID」時，畫面會顯示紅色風險警語</p></figcaption></figure>

### 4. 取得簽章密鑰 <a href="#signing-secret" id="signing-secret"></a>

選擇簽章模式並儲存設定後，平台會產生一組簽章密鑰。在密鑰欄位可以：

* 點擊 「 <mark style="color:blue;">顯示</mark> 」 檢視完整密鑰（預設遮罩）
* 點擊 「 <mark style="color:blue;">複製</mark> 」 交給您的工程師
* 點擊 「 <mark style="color:blue;">重新產生</mark> 」 換發新密鑰

{% hint style="warning" %}
密鑰請存放在您的伺服器環境變數，切勿寫入前端程式碼。重新產生後舊密鑰立即失效，您的後端必須同步更換，否則簽章一律驗不過。
{% endhint %}

### 5. 設定簽章有效期限 <a href="#signature-ttl" id="signature-ttl"></a>

可選 1、5、15 分鐘，預設 5 分鐘。逾期或已使用過的簽章會被拒絕。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-2e4eb936b04e8a0ffea6d1aa0dac6fa5b6ec0407%2Fsourceid-04-secret-ttl-snippets.png?alt=media" alt=""><figcaption><p>簽章密鑰、簽章有效期限、整合範例與行為預覽</p></figcaption></figure>

{% hint style="info" %}
有效期限限制的是「這組簽章多久內可以用來開啟對話」，不是對話的存續時間。使用者換得身分後正常對話，不會在 5 分鐘後被登出。
{% endhint %}

## <mark style="color:blue;">三、您的工程師如何串接</mark> <a href="#integration" id="integration"></a>

後台的 「 <mark style="color:blue;">整合範例</mark> 」 區塊會帶入此對話平台的識別碼，可直接複製使用。完整的參數說明、驗證規則與疑難排解，請交給您的工程師參考[Web Chat 嵌入與 SDK · 簽章驗證](https://docs.maiagent.ai/tech/api-integration/web-chat-sdk#source-id-signature)。

### 1. 後端計算簽章 <a href="#backend-signature" id="backend-signature"></a>

簽章內容為 `HMAC-SHA256(密鑰, "{對話平台識別碼}.{Source ID}.{時間戳}")`，以 hex 字串傳遞。時間戳為 Unix 秒（UTC），由您的後端產生。

{% tabs %}
{% tab title="PHP" %}
{% code overflow="wrap" %}

```php
$ts  = time();
$sig = hash_hmac('sha256', "{$webChatId}.{$sourceId}.{$ts}", $SIGNING_SECRET);
```

{% endcode %}
{% endtab %}

{% tab title="Node" %}
{% code overflow="wrap" %}

```javascript
const ts = Math.floor(Date.now() / 1000);
const sig = crypto.createHmac('sha256', SIGNING_SECRET)
  .update(`${webChatId}.${sourceId}.${ts}`).digest('hex');
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code overflow="wrap" %}

```python
ts = int(time.time())
sig = hmac.new(SIGNING_SECRET.encode(),
  f"{web_chat_id}.{source_id}.{ts}".encode(), hashlib.sha256).hexdigest()
```

{% endcode %}
{% endtab %}
{% endtabs %}

### 2. 前端帶入嵌入腳本 <a href="#frontend-setup-auth" id="frontend-setup-auth"></a>

{% code overflow="wrap" %}

```javascript
window.MaiAgent.setupAuth({ sourceId, name, ts, sig });
```

{% endcode %}

### 3. 串接注意事項 <a href="#integration-notes" id="integration-notes"></a>

* **每次進場都要重新簽**：同一組簽章只能成功使用一次，嵌入端不得快取簽章。
* **簽章要在後端算**：密鑰一旦出現在前端程式碼就等於公開。
* **時鐘要準**：系統允許 60 秒的時鐘偏差，時間戳超出此範圍會被拒絕。
* **對話平台識別碼要正確**：簽章內含對話平台識別碼，以其他對話平台的識別碼計算的簽章不會通過。

## <mark style="color:blue;">四、行為對照</mark> <a href="#behavior" id="behavior"></a>

| 進來的請求                            | 結果           |
| -------------------------------- | ------------ |
| 帶 Source ID ＋ 有效簽章               | 直接對話，不出現登入畫面 |
| 帶 Source ID，簽章錯誤或逾期              | 拒絕           |
| 同一組簽章重複使用                        | 第一次成功，第二次拒絕  |
| 未帶 Source ID（含直接開啟公開網址）          | 導向登入頁        |
| 驗證方式為「僅憑 Source ID」＋ 帶 Source ID | 直接對話，不驗簽章    |
| 本開關關閉                            | 維持原本的登入設定行為  |

{% hint style="info" %}
所有拒絕情境對外回應一致，不會透露失敗原因，也不會透露某個 Source ID 是否存在。原因只出現在後台的驗章失敗紀錄。
{% endhint %}

## <mark style="color:blue;">五、驗章失敗紀錄</mark> <a href="#verification-failures" id="verification-failures"></a>

串接不順時，在設定區塊點擊 「 <mark style="color:blue;">查看驗章失敗紀錄</mark> 」 即可看到最近的失敗事件，供您的工程師自助排查。紀錄不含密鑰與完整簽章。

<figure><img src="https://1593648278-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fmzb5NG9GDzFP2YDKeYVl%2Fuploads%2Fgit-blob-97836892fb059355c1a832478e76d6795a3a1719%2Fsourceid-05-verification-failures.png?alt=media" alt=""><figcaption><p>展開後的驗章失敗紀錄</p></figcaption></figure>

| 原因                 | 常見成因                         |
| ------------------ | ---------------------------- |
| 簽章逾期               | 伺服器時鐘偏移，或嵌入端快取了簽章            |
| 時間戳超出未來容許範圍        | 伺服器時鐘快了超過 60 秒               |
| 簽章不符（密鑰可能不一致）      | 後端用的密鑰與後台不同，或簽章字串組法有誤        |
| 缺少時間戳或簽章           | 嵌入端沒帶 `ts` 或 `sig`           |
| 簽章已被使用             | 同一組簽章送了第二次                   |
| 防重放快取無法使用          | 平台端暫時性狀況，系統採取拒絕而非放行          |
| Source ID 對應到多位聯絡人 | 該對話平台存在同一 Source ID 的重複聯絡人資料 |

## <mark style="color:blue;">六、常見問題</mark> <a href="#faq" id="faq"></a>

<details>

<summary>簽章有效期限到了，使用者的對話會中斷嗎？</summary>

不會。有效期限只限制「多久內可以用這組簽章換取身分」。換到身分之後，對話的存續時間依 Web Chat 既有機制，不受簽章期限影響。

</details>

<details>

<summary>同一個 Source ID 會對應到多位聯絡人嗎？</summary>

在同一個對話平台內，一個 Source ID 只會對應一位聯絡人。如果同一組 Source ID 用在多個對話平台，各平台會各自有一位聯絡人，對話紀錄彼此獨立。

</details>

<details>

<summary>開啟這個設定會影響現有的嵌入嗎？</summary>

本設定預設關閉，既有對話平台的行為完全不變。開啟後若選擇簽章模式，未帶 `ts` 與 `sig` 的請求會被導向登入頁，因此請與您的工程師確認嵌入端已同步更新後再開啟。

</details>

<details>

<summary>使用者在我的網站登出後，還能繼續對話嗎？</summary>

已經換取到身分的使用者仍可繼續該次對話。您能控制的是發放端：使用者登出後不再簽發新的簽章，他就無法再換取身分。若貴端需要「登出即失效」，請與我們聯繫，我們會另行評估做法。

</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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.maiagent.ai/conversations/web-chat/source-id-access.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
