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_...
API キーと Client ID は、WorkOS Dashboard の API Keys と Applications でそれぞれ確認できます。
詳しい設定手順については、使用するプラットフォーム向けの WorkOS ドキュメントを参照してください。
インストールインストールへの直接リンク
MastraAuthWorkos クラスを使用するには、事前に @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 メンバーシップの読み込みへの直接リンク
MastraFGAWorkos を使用する場合は、fetchMemberships: true を設定します。これにより認証時にユーザーの WorkOS Organization メンバーシップが読み込まれ、FGA チェックで正しい Organization メンバーシップ 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 テンプレートへの直接リンク
マシン間通信やサービスアカウントからのアクセスでは、WorkOS のカスタム JWT テンプレートによって検証された Bearer トークンのクレームを信頼するように MastraAuthWorkos を設定できます。
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 テンプレートに organizationMembershipId、テナント ID、サービスプリンシパル識別子など、Mastra が必要とする正確な FGA コンテキストがすでに含まれている場合に役立ちます。trustJwtClaims を有効にすると、Bearer トークンが workos.userManagement.getUser() を経由する用途でない場合、Mastra は検証済みのクレームを代わりに使用できます。
カスタム認可カスタム認可への直接リンク
より厳格な認可が必要な場合は、MastraAuthWorkos をサブクラス化し、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 ドキュメントを参照してください。
MastraClient の設定configuring-mastraclientへの直接リンク
auth を有効にすると、MastraClient から送信するすべてのリクエストで、Authorization ヘッダーに有効な 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 ヘッダーでは、アクセストークンに 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"
}'