WorkOS
@mastra/auth-workos 套件使用 WorkOS 為 Mastra 提供身份驗證。它會使用 WorkOS 存取權杖驗證傳入的請求,並透過 auth 選項與 Mastra 伺服器整合。
先決條件先決條件 的直接連結
此範例使用 WorkOS 身份驗證。請確保你已:
- 在 workos.com 建立 WorkOS 帳戶
- 在 WorkOS Dashboard 設定 Application
- 設定重新導向 URI 及允許的來源
- 設定 Organization,並按需要設定用戶角色
WORKOS_API_KEY=sk_live_...
WORKOS_CLIENT_ID=client_...
你可以分別在 WorkOS Dashboard 的 API Keys 和 Applications 下找到 API 金鑰及 Client ID。
如需詳細設定指引,請參閱適用於你所用平台的 WorkOS 文檔。
安裝安裝 的直接連結
使用 MastraAuthWorkos class 前,必須先安裝 @mastra/auth-workos 套件。
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/auth-workos@latest
pnpm add @mastra/auth-workos@latest
yarn add @mastra/auth-workos@latest
bun add @mastra/auth-workos@latest
使用範例使用範例 的直接連結
配合環境變數的基本用法配合環境變數的基本用法 的直接連結
import { Mastra } from '@mastra/core'
import { MastraAuthWorkos } from '@mastra/auth-workos'
export const mastra = new Mastra({
server: {
auth: new MastraAuthWorkos(),
},
})
自訂設定自訂設定 的直接連結
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 成員資格載入 FGA 成員資格 的直接連結
設定 fetchMemberships: true 是使用 MastraFGAWorkos 時的必要步驟。這會指示身份驗證 Provider 在身份驗證期間載入用戶的 WorkOS 組織成員資格,讓 FGA 檢查能夠解析正確的組織成員資格 ID。
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 範本服務權杖與自訂 JWT 範本 的直接連結
如需機器對機器或服務帳戶存取,你可以設定 MastraAuthWorkos,使其信任來自 WorkOS 自訂 JWT 範本且已驗證的 bearer token claim。
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():
import { MastraAuthWorkos } from '@mastra/auth-workos'
import type { HonoRequest } from 'hono'
class AdminOnlyWorkosAuth extends MastraAuthWorkos {
async authorizeUser(user: any, _request: HonoRequest): Promise<boolean> {
return user?.metadata?.role === 'admin'
}
}
const workosAuth = new AdminOnlyWorkosAuth({
apiKey: process.env.WORKOS_API_KEY,
clientId: process.env.WORKOS_CLIENT_ID,
})
請參閱 MastraAuthWorkos,了解所有可用的設定選項。
客戶端設定客戶端設定 的直接連結
使用 WorkOS 身份驗證時,你需要實作 WorkOS 身份驗證流程,以授權碼換取存取權杖,然後在 Mastra 請求中使用該權杖。
安裝 WorkOS SDK安裝 WorkOS SDK 的直接連結
首先,在應用程式中安裝 WorkOS SDK:
- npm
- pnpm
- Yarn
- Bun
npm install @workos-inc/node
pnpm add @workos-inc/node
yarn add @workos-inc/node
bun add @workos-inc/node
以授權碼換取存取權杖以授權碼換取存取權杖 的直接連結
用戶完成 WorkOS 身份驗證流程並帶同授權碼返回後,請以該授權碼換取存取權杖:
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 文檔。
設定 MastraClientconfiguring-mastraclient 的直接連結
啟用 auth 後,所有透過 MastraClient 發出的請求都必須在 Authorization header 中包含有效的 WorkOS 存取權杖:
import { MastraClient } from '@mastra/client-js'
export const createMastraClient = (accessToken: string) => {
return new MastraClient({
baseUrl: 'https://<mastra-api-url>',
headers: {
Authorization: `Bearer ${accessToken}`,
},
})
}
在 Authorization header 中,存取權杖前必須加上 Bearer。
如需更多設定選項,請參閱 Mastra Client SDK。
發出已通過身份驗證的請求發出已通過身份驗證的請求 的直接連結
使用 WorkOS 存取權杖設定 MastraClient 後,便可以發出已通過身份驗證的請求:
- React
- cURL
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 -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-workos-access-token>" \
-d '{
"messages": "Weather in London"
}'