JSON Web Token
MastraJwtAuth クラスは、JSON Web Token(JWT)を使用した軽量な Mastra 認証メカニズムを提供します。共有シークレットに基づいて受信リクエストを検証し、auth オプションを使用して Mastra サーバーと統合します。
インストールインストールへの直接リンク
MastraJwtAuth クラスを使用するには、事前に @mastra/auth パッケージをインストールする必要があります。
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/auth@latest
pnpm add @mastra/auth@latest
yarn add @mastra/auth@latest
bun add @mastra/auth@latest
JWT の作成JWT の作成への直接リンク
Mastra サーバーへのリクエストを認証するには、MASTRA_JWT_SECRET で署名された有効な JSON Web Token(JWT)が必要です。
最も簡単な生成方法は、jwt.io を使用することです。
- JWT Encoder を選択します。
- Sign JWT: Secret セクションまでスクロールします。
- シークレットを入力します(例:
supersecretdevkeythatishs256safe!)。 - Generate example をクリックして有効な JWT を作成します。
- 生成されたトークンをコピーし、
.envファイルのMASTRA_JWT_TOKENに設定します。
使用例使用例への直接リンク
生成した JWT を使って、Mastra サーバーで MastraJwtAuth を設定します。
src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { MastraJwtAuth } from '@mastra/auth'
export const mastra = new Mastra({
server: {
auth: new MastraJwtAuth({
secret: process.env.MASTRA_JWT_SECRET,
}),
},
})
利用可能なすべての設定オプションについては、MastraJwtAuth を参照してください。
Studio で Settings を開き、Headers の "Add Header" ボタンを選択します。ヘッダー名に Authorization、値に Bearer <your-jwt> を入力します。
MastraClient の設定configuring-mastraclientへの直接リンク
auth を有効にすると、MastraClient から送信するすべてのリクエストで、Authorization ヘッダーに有効な JWT を含める必要があります。
lib/mastra/mastra-client.ts
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: 'https://<mastra-api-url>',
headers: {
Authorization: `Bearer ${process.env.MASTRA_JWT_TOKEN}`,
},
})
その他の設定オプションについては、Mastra Client SDK を参照してください。
認証済みリクエストの送信認証済みリクエストの送信への直接リンク
MastraClient の設定後は、フロントエンドアプリケーションから認証済みリクエストを送信できます。ローカルで手早くテストする場合は curl も使用できます。
- React
- cURL
src/components/test-agent.tsx
import { mastraClient } from '../../lib/mastra-client'
export const TestAgent = () => {
async function handleClick() {
const agent = mastraClient.getAgent('weatherAgent')
const response = await agent.generate('Weather in London')
console.log(response)
}
return <button onClick={handleClick}>Test Agent</button>
}
curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-jwt>" \
-d '{
"messages": "Weather in London"
}'