> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # WorkOS `@mastra/auth-workos` 套件使用 WorkOS 為 Mastra 提供身份驗證。它會使用 WorkOS 存取權杖驗證傳入的請求,並透過 `auth` 選項與 Mastra 伺服器整合。 ## 先決條件 此範例使用 WorkOS 身份驗證。請確保你已: 1. 在 [workos.com](https://workos.com/) 建立 WorkOS 帳戶 2. 在 WorkOS Dashboard 設定 Application 3. 設定重新導向 URI 及允許的來源 4. 設定 Organization,並按需要設定用戶角色 ```env WORKOS_API_KEY=sk_live_... WORKOS_CLIENT_ID=client_... ``` > **備註:** 你可以分別在 WorkOS Dashboard 的 API Keys 和 Applications 下找到 API 金鑰及 Client ID。 > > 如需詳細設定指引,請參閱適用於你所用平台的 [WorkOS 文檔](https://workos.com/docs)。 ## 安裝 使用 `MastraAuthWorkos` class 前,必須先安裝 `@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 成員資格 設定 `fetchMemberships: true` 是使用 [`MastraFGAWorkos`](https://mastra.zisheng.pro/zh-HK/docs/server/auth/fga) 時的必要步驟。這會指示身份驗證 Provider 在身份驗證期間載入用戶的 WorkOS 組織成員資格,讓 FGA 檢查能夠解析正確的組織成員資格 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()` 呼叫。 ### 服務權杖與自訂 JWT 範本 如需機器對機器或服務帳戶存取,你可以設定 `MastraAuthWorkos`,使其信任來自 WorkOS 自訂 JWT 範本且已驗證的 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 範本已包含 Mastra 所需的確切 FGA context,例如 `organizationMembershipId`、tenant ID 或 service principal 識別碼,此設定便很有用。啟用 `trustJwtClaims` 後,如果 bearer token 並非用於透過 `workos.userManagement.getUser()` 往返處理,Mastra 可以改用這些已驗證的 claim。 ### 自訂授權 如需更嚴格的授權,請建立 `MastraAuthWorkos` 的 subclass,並 override `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-HK/reference/auth/workos),了解所有可用的設定選項。 ## 客戶端設定 使用 WorkOS 身份驗證時,你需要實作 WorkOS 身份驗證流程,以授權碼換取存取權杖,然後在 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 ``` ### 以授權碼換取存取權杖 用戶完成 WorkOS 身份驗證流程並帶同授權碼返回後,請以該授權碼換取存取權杖: ```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 存取權杖: ```typescript import { MastraClient } from '@mastra/client-js' export const createMastraClient = (accessToken: string) => { return new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${accessToken}`, }, }) } ``` > **資訊:** 在 Authorization header 中,存取權杖前必須加上 `Bearer`。 > > 如需更多設定選項,請參閱 [Mastra Client SDK](https://mastra.zisheng.pro/zh-HK/docs/server/mastra-client)。 ### 發出已通過身份驗證的請求 使用 WorkOS 存取權杖設定 `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" }' ```