> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt
# Better Auth
`@mastra/auth-better-auth` パッケージは、Better Auth を使用した Mastra の認証を提供します。Better Auth インスタンスを使用して受信リクエストを検証し、`server.auth` オプションで Mastra サーバーと統合します。
## 前提条件
この例では Better Auth を使用します。Better Auth インスタンスが設定され、環境変数がセットされていることを確認してください。
```env
# Required by Better Auth
BETTER_AUTH_SECRET=... # at least 32 chars
BETTER_AUTH_URL=http://localhost:3000
# Example DB URL used by the snippet below (adjust for your setup)
DATABASE_URL=postgres://...
```
> **注記:** Better Auth では、セキュリティと安定性のために `baseURL` を明示的に設定する(または `BETTER_AUTH_URL` を使用する)ことを推奨しています。
Better Auth のハンドラーをまだマウントしていない場合(アプリでユーザーのサインインやセッションの作成を可能にするため)、[Better Auth のインストールガイド](https://www.better-auth.com/docs/installation)に従って `/api/auth/*` ルート(または設定したベースパス)をマウントしてください。
## インストール
`@mastra/auth-better-auth` パッケージをインストールします。
**npm**:
```bash
npm install @mastra/auth-better-auth
```
**pnpm**:
```bash
pnpm add @mastra/auth-better-auth
```
**Yarn**:
```bash
yarn add @mastra/auth-better-auth
```
**Bun**:
```bash
bun add @mastra/auth-better-auth
```
## 使用例
まず、Better Auth インスタンスを作成します。
```ts
import { betterAuth } from 'better-auth'
export const auth = betterAuth({
database: {
provider: 'postgresql',
url: process.env.DATABASE_URL!,
},
emailAndPassword: {
enabled: true,
},
baseURL: process.env.BETTER_AUTH_URL,
secret: process.env.BETTER_AUTH_SECRET,
})
```
次に、Mastra で使用します。
```ts
import { Mastra } from '@mastra/core'
import { MastraAuthBetterAuth } from '@mastra/auth-better-auth'
import { auth } from '@/lib/auth'
const mastraAuth = new MastraAuthBetterAuth({
auth,
})
export const mastra = new Mastra({
server: {
auth: mastraAuth,
},
})
```
利用可能なすべての設定オプションについては、[MastraAuthBetterAuth](https://mastra.zisheng.pro/ja/reference/auth/better-auth) を参照してください。
## カスタム認可
```ts
const mastraAuth = new MastraAuthBetterAuth({
auth,
async authorizeUser(user) {
// Example: only allow verified emails
return user?.user?.emailVerified === true
},
})
```
## ルート設定
```ts
const mastraAuth = new MastraAuthBetterAuth({
auth,
public: ['/health', '/api/status'],
protected: ['/api/*', '/admin/*'],
})
```
### マッチングルール
- `public` と `protected` には、完全一致パス、ワイルドカードパターン(`/api/*` など)、パスパラメーター(`/users/:id` など)を指定できます。
- メソッド固有のルールには、`["/api/agents", ["GET", "POST"]]` のようなタプルを使用します。
- ルートが `public` と `protected` の両方に一致する場合は `public` が優先され、認証は不要です。
- どちらにも一致しない場合、ルートはデフォルトで保護対象として扱われます(ルートに `requiresAuth: false` が明示的に指定されている場合を除きます)。
## クライアント側の設定
認証を有効にすると、Mastra の組み込みルートへのリクエストに認証が必要になります。つまり、実際には Better Auth の設定で認証済みリクエストに使用する認証情報をクライアントから送信する必要があります。
### Cookie セッション(推奨)
Better Auth の設定で Cookie を使用する場合は、認証情報を送信するようにクライアントを設定します。クロスオリジンリクエスト(たとえば、`:3000` の Next.js から `:4111` の Mastra を呼び出す場合)では、Mastra サーバーで CORS の認証情報を有効にします。
```ts
export const mastra = new Mastra({
server: {
auth: mastraAuth,
cors: {
origin: 'http://localhost:3000', // your frontend origin
credentials: true,
},
},
})
```
次に、認証情報を含めるようにクライアントを設定します。
```ts
import { MastraClient } from '@mastra/client-js'
export const mastraClient = new MastraClient({
baseUrl: 'http://localhost:4111',
credentials: 'include',
})
```
API を直接呼び出す場合も、`fetch` に認証情報を含めます。
```ts
await fetch('http://localhost:4111/api/agents/weatherAgent/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({ messages: 'Weather in London' }),
})
```
### Bearer トークン
署名済みセッショントークンを Bearer トークンとして渡せます。Better Auth のクライアントセッションから取得し、`Authorization` ヘッダーに含めます。
```ts
import { MastraClient } from '@mastra/client-js'
import { authClient } from './auth-client' // your Better Auth client
const session = await authClient.getSession()
export const mastraClient = new MastraClient({
baseUrl: 'http://localhost:4111',
headers: {
Authorization: `Bearer ${session.data?.session.token}`,
},
})
```
その他の設定オプションについては、[Mastra Client SDK](https://mastra.zisheng.pro/ja/docs/server/mastra-client) を参照してください。
### 認証済みリクエストの送信
**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"
}'
```
## トラブルシューティング
- **すべてのリクエストで 401 が発生する**: Better Auth のハンドラーがマウントされ、アプリで有効なセッションを作成できることを確認します。クライアントがセッション Cookie または `Authorization: Bearer ` ヘッダーのいずれかを送信していることを確認してください。
- **クロスオリジンで Cookie が送信されない**: `MastraClient` で `credentials: "include"` を設定し、フロントエンドのオリジンと `credentials: true` を指定して `server.cors` を設定します。
- **Bearer トークンが拒否される**: 生のトークンや未署名のトークンではなく、(`authClient.getSession()` から取得した)完全な署名済みセッショントークンを渡していることを確認します。
- **ベース URL の問題**: `betterAuth({ ... })` で `baseURL` を設定するか、`BETTER_AUTH_URL` を設定します。
- **DB 接続エラー**: `DATABASE_URL` とデータベース Provider の設定を確認します。