跳至主要內容

WorkOS

@mastra/auth-workos 套件使用 WorkOS 為 Mastra 提供身份驗證。它會使用 WorkOS 存取權杖驗證傳入的請求,並透過 auth 選項與 Mastra 伺服器整合。

先決條件
先決條件 的直接連結

此範例使用 WorkOS 身份驗證。請確保你已:

  1. 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 文檔

安裝
安裝 的直接連結

使用 MastraAuthWorkos class 前,必須先安裝 @mastra/auth-workos 套件。

npm install @mastra/auth-workos@latest

使用範例
使用範例 的直接連結

配合環境變數的基本用法
配合環境變數的基本用法 的直接連結

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraAuthWorkos } from '@mastra/auth-workos'

export const mastra = new Mastra({
server: {
auth: new MastraAuthWorkos(),
},
})

自訂設定
自訂設定 的直接連結

src/mastra/index.ts
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。

src/mastra/auth.ts
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,
})

fetchMembershipsfalse 時,Mastra 會在每個已通過身份驗證的請求中略過額外的 WorkOS listOrganizationMemberships() 呼叫。

服務權杖與自訂 JWT 範本
服務權杖與自訂 JWT 範本 的直接連結

如需機器對機器或服務帳戶存取,你可以設定 MastraAuthWorkos,使其信任來自 WorkOS 自訂 JWT 範本且已驗證的 bearer token claim。

src/mastra/auth.ts
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()

src/mastra/auth.ts
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 install @workos-inc/node

以授權碼換取存取權杖
以授權碼換取存取權杖 的直接連結

用戶完成 WorkOS 身份驗證流程並帶同授權碼返回後,請以該授權碼換取存取權杖:

lib/auth.ts
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 文檔

設定 MastraClient
configuring-mastraclient 的直接連結

啟用 auth 後,所有透過 MastraClient 發出的請求都必須在 Authorization header 中包含有效的 WorkOS 存取權杖:

lib/mastra/mastra-client.ts
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 後,便可以發出已通過身份驗證的請求:

src/api/agents.ts
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
}