跳至主要內容

WorkOS

@mastra/auth-workos 套件透過 WorkOS 為 Mastra 提供驗證功能。它會使用 WorkOS access token 驗證傳入的請求,並透過 auth 選項與 Mastra 伺服器整合。

事前準備
「事前準備」的直接連結

此範例使用 WorkOS 驗證。請務必完成下列事項:

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

安裝
「安裝」的直接連結

使用 MastraAuthWorkos 類別前,必須先安裝 @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 membership
「載入 FGA membership」的直接連結

使用 MastraFGAWorkos 時,請設定 fetchMemberships: true。這會指示 auth Provider 在驗證期間載入使用者的 WorkOS organization membership,讓 FGA 檢查可以解析正確的 organization membership 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() 呼叫。

Service token 與自訂 JWT template
「Service token 與自訂 JWT template」的直接連結

針對機器對機器或 service account 存取,你可以設定 MastraAuthWorkos,使其信任來自 WorkOS 自訂 JWT template、且已驗證的 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 template 已包含 Mastra 所需的確切 FGA context(例如 organizationMembershipId、tenant ID 或 service principal 識別碼)時,此設定很實用。啟用 trustJwtClaims 後,如果 bearer token 並非用於透過 workos.userManagement.getUser() 來回處理,Mastra 可以改用這些已驗證的 claim。

自訂授權
「自訂授權」的直接連結

如果需要更嚴格的授權,請建立 MastraAuthWorkos 的子類別並覆寫 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 驗證流程,以授權碼交換 access token,再將該 token 用於 Mastra 請求。

安裝 WorkOS SDK
「安裝 WorkOS SDK」的直接連結

首先,在應用程式中安裝 WorkOS SDK:

npm install @workos-inc/node

以授權碼交換 access token
「以授權碼交換 access token」的直接連結

使用者完成 WorkOS 驗證流程並帶著授權碼返回後,請用該授權碼交換 access token:

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 access token:

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}`,
},
})
}
資訊

Access token 在 Authorization header 中必須以 Bearer 為前綴。

如需更多設定選項,請參閱 Mastra Client SDK

發出已驗證的請求
「發出已驗證的請求」的直接連結

使用 WorkOS access token 設定 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
}