> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # JSON Web Token `MastraJwtAuth` クラスは、JSON Web Token(JWT)を使用した軽量な Mastra 認証メカニズムを提供します。共有シークレットに基づいて受信リクエストを検証し、`auth` オプションを使用して Mastra サーバーと統合します。 ## インストール `MastraJwtAuth` クラスを使用するには、事前に `@mastra/auth` パッケージをインストールする必要があります。 **npm**: ```bash npm install @mastra/auth@latest ``` **pnpm**: ```bash pnpm add @mastra/auth@latest ``` **Yarn**: ```bash yarn add @mastra/auth@latest ``` **Bun**: ```bash bun add @mastra/auth@latest ``` ## JWT の作成 Mastra サーバーへのリクエストを認証するには、`MASTRA_JWT_SECRET` で署名された有効な JSON Web Token(JWT)が必要です。 最も簡単な生成方法は、[jwt.io](https://www.jwt.io/) を使用することです。 1. **JWT Encoder** を選択します。 2. **Sign JWT: Secret** セクションまでスクロールします。 3. シークレットを入力します(例: `supersecretdevkeythatishs256safe!`)。 4. **Generate example** をクリックして有効な JWT を作成します。 5. 生成されたトークンをコピーし、`.env` ファイルの `MASTRA_JWT_TOKEN` に設定します。 ## 使用例 生成した JWT を使って、Mastra サーバーで `MastraJwtAuth` を設定します。 ```typescript 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](https://mastra.zisheng.pro/ja/reference/auth/jwt) を参照してください。 [Studio](https://mastra.zisheng.pro/ja/docs/studio/overview) で **Settings** を開き、**Headers** の **"Add Header"** ボタンを選択します。ヘッダー名に `Authorization`、値に `Bearer ` を入力します。 ## `MastraClient` の設定 `auth` を有効にすると、`MastraClient` から送信するすべてのリクエストで、`Authorization` ヘッダーに有効な JWT を含める必要があります。 ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: 'https://', headers: { Authorization: `Bearer ${process.env.MASTRA_JWT_TOKEN}`, }, }) ``` その他の設定オプションについては、[Mastra Client SDK](https://mastra.zisheng.pro/ja/docs/server/mastra-client) を参照してください。 ### 認証済みリクエストの送信 `MastraClient` の設定後は、フロントエンドアプリケーションから認証済みリクエストを送信できます。ローカルで手早くテストする場合は `curl` も使用できます。 **React**: ```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 } ``` **cURL**: ```bash curl -X POST http://localhost:4111/api/agents/weatherAgent/generate \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "messages": "Weather in London" }' ```