> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # WorkOS `@mastra/auth-workos` 套件透過 WorkOS 為 Mastra 提供驗證功能。它會使用 WorkOS access token 驗證傳入的請求,並透過 `auth` 選項與 Mastra 伺服器整合。 ## 事前準備 此範例使用 WorkOS 驗證。請務必完成下列事項: 1. 在 [workos.com](https://workos.com/) 建立 WorkOS 帳號 2. 在 WorkOS Dashboard 中設定 Application 3. 設定 redirect URI 與允許的 origin 4. 設定 Organization,並依需要設定使用者角色 ```env WORKOS_API_KEY=sk_live_... WORKOS_CLIENT_ID=client_... ``` > **備註:** 你可以分別在 WorkOS Dashboard 的 API Keys 與 Applications 中找到 API key 和 Client ID。 > > 如需詳細設定指示,請參閱適用於你所用平台的 [WorkOS 文件](https://workos.com/docs)。 ## 安裝 使用 `MastraAuthWorkos` 類別前,必須先安裝 `@mastra/auth-workos` 套件。 **npm**: ```bash npm install @mastra/auth-workos@latest ``` **pnpm**: ```bash pnpm add @mastra/auth-workos@latest ``` **Yarn**: ```bash yarn add @mastra/auth-workos@latest ``` **Bun**: ```bash bun add @mastra/auth-workos@latest ``` ## 使用範例 ### 搭配環境變數的基本用法 ```typescript import { Mastra } from '@mastra/core' import { MastraAuthWorkos } from '@mastra/auth-workos' export const mastra = new Mastra({ server: { auth: new MastraAuthWorkos(), }, }) ``` ### 自訂設定 ```typescript import { Mastra } from '@mastra/core' import { MastraAuthWorkos } from '@mastra/auth-workos' export const mastra = new Mastra({ server: { auth: new MastraAuthWorkos({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, }), }, }) ``` ## 設定 ### 預設授權 `MastraAuthWorkos` 預設會授予任何已驗證 WorkOS 使用者存取權。當解析出的使用者物件同時包含 Mastra 使用者 ID 與 WorkOS 使用者 ID 時,授權檢查便會成功。 ### 載入 FGA membership 使用 [`MastraFGAWorkos`](https://mastra.zisheng.pro/zh-TW/docs/server/auth/fga) 時,請設定 `fetchMemberships: true`。這會指示 auth Provider 在驗證期間載入使用者的 WorkOS organization membership,讓 FGA 檢查可以解析正確的 organization membership ID。 ```typescript import { MastraAuthWorkos, MastraFGAWorkos } from '@mastra/auth-workos' const workosAuth = new MastraAuthWorkos({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, fetchMemberships: true, }) const workosFga = new MastraFGAWorkos({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, }) ``` 當 `fetchMemberships` 為 `false` 時,Mastra 會略過每個已驗證請求額外進行的 WorkOS `listOrganizationMemberships()` 呼叫。 ### Service token 與自訂 JWT template 針對機器對機器或 service account 存取,你可以設定 `MastraAuthWorkos`,使其信任來自 WorkOS 自訂 JWT template、且已驗證的 bearer-token claim。 ```typescript import { MastraAuthWorkos } from '@mastra/auth-workos' const workosAuth = new MastraAuthWorkos({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, redirectUri: process.env.WORKOS_REDIRECT_URI, trustJwtClaims: true, jwtClaims: { organizationId: 'org_id', organizationMembershipId: 'urn:mastra:organization_membership_id', }, }) ``` 當 JWT template 已包含 Mastra 所需的確切 FGA context(例如 `organizationMembershipId`、tenant ID 或 service principal 識別碼)時,此設定很實用。啟用 `trustJwtClaims` 後,如果 bearer token 並非用於透過 `workos.userManagement.getUser()` 來回處理,Mastra 可以改用這些已驗證的 claim。 ### 自訂授權 如果需要更嚴格的授權,請建立 `MastraAuthWorkos` 的子類別並覆寫 `authorizeUser()`: ```typescript import { MastraAuthWorkos } from '@mastra/auth-workos' import type { HonoRequest } from 'hono' class AdminOnlyWorkosAuth extends MastraAuthWorkos { async authorizeUser(user: any, _request: HonoRequest): Promise { return user?.metadata?.role === 'admin' } } const workosAuth = new AdminOnlyWorkosAuth({ apiKey: process.env.WORKOS_API_KEY, clientId: process.env.WORKOS_CLIENT_ID, }) ``` 請參閱 [MastraAuthWorkos](https://mastra.zisheng.pro/zh-TW/reference/auth/workos),瞭解所有可用的設定選項。 ## 用戶端設定 使用 WorkOS 驗證時,你需要實作 WorkOS 驗證流程,以授權碼交換 access token,再將該 token 用於 Mastra 請求。 ### 安裝 WorkOS SDK 首先,在應用程式中安裝 WorkOS SDK: **npm**: ```bash npm install @workos-inc/node ``` **pnpm**: ```bash pnpm add @workos-inc/node ``` **Yarn**: ```bash yarn add @workos-inc/node ``` **Bun**: ```bash bun add @workos-inc/node ``` ### 以授權碼交換 access token 使用者完成 WorkOS 驗證流程並帶著授權碼返回後,請用該授權碼交換 access token: ```typescript import { WorkOS } from '@workos-inc/node' const workos = new WorkOS(process.env.WORKOS_API_KEY) export const authenticateWithWorkos = async (code: string, clientId: string) => { const authenticationResponse = await workos.userManagement.authenticateWithCode({ code, clientId, }) return authenticationResponse.accessToken } ``` > **備註:** 如需更多驗證方式與設定選項,請參閱 [WorkOS User Management 文件](https://workos.com/docs/authkit/vanilla/nodejs)。 ## 設定 `MastraClient` 啟用 `auth` 後,所有透過 `MastraClient` 發出的請求都必須在 `Authorization` header 中包含有效的 WorkOS access token: ```typescript import { MastraClient } from '@mastra/client-js' export const createMastraClient = (accessToken: string) => { return new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${accessToken}`, }, }) } ``` > **資訊:** Access token 在 Authorization header 中必須以 `Bearer` 為前綴。 > > 如需更多設定選項,請參閱 [Mastra Client SDK](https://mastra.zisheng.pro/zh-TW/docs/server/mastra-client)。 ### 發出已驗證的請求 使用 WorkOS access token 設定 `MastraClient` 後,即可傳送已驗證的請求: **React**: ```typescript import { WorkOS } from '@workos-inc/node' import { MastraClient } from '@mastra/client-js' const workos = new WorkOS(process.env.WORKOS_API_KEY) export const callMastraWithWorkos = async (code: string, clientId: string) => { const authenticationResponse = await workos.userManagement.authenticateWithCode({ code, clientId, }) const token = authenticationResponse.accessToken const mastra = new MastraClient({ baseUrl: 'http://localhost:4111', headers: { Authorization: `Bearer ${token}`, }, }) const weatherAgent = mastra.getAgent('weatherAgent') const response = await weatherAgent.generate("What's the weather like in Nairobi") return response.text } ``` **cURL**: ```bash curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "messages": "Weather in London" }' ```