jpskill.com
🛠️ 開発・MCP コミュニティ

configuring-better-auth

Implement OAuth 2.1 / OIDC authentication using Better Auth with MCP assistance. Use when setting up a centralized auth server (SSO provider), implementing SSO clients in Next.js apps, configuring PKCE flows, or managing tokens with JWKS verification. Uses Better Auth MCP for guided setup. NOT when using simple session-only auth without OAuth/OIDC requirements.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o configuring-better-auth.zip https://jpskill.com/download/17290.zip && unzip -o configuring-better-auth.zip && rm configuring-better-auth.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17290.zip -OutFile "$d\configuring-better-auth.zip"; Expand-Archive "$d\configuring-better-auth.zip" -DestinationPath $d -Force; ri "$d\configuring-better-auth.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して configuring-better-auth.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → configuring-better-auth フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
4

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Better Auth OAuth/OIDC

Better Auth を使用して、認証サーバーまたは SSO クライアントとして、集中認証を実装します。

MCP サーバーのセットアップ

Better Auth は、ガイド付き構成のために Chonkie を利用した MCP サーバーを提供します。

claude mcp add --transport http better-auth https://mcp.chonkie.ai/better-auth/better-auth-builder/mcp

または settings.json で:

{
  "mcpServers": {
    "better-auth": {
      "type": "http",
      "url": "https://mcp.chonkie.ai/better-auth/better-auth-builder/mcp"
    }
  }
}

MCP を使用するべき時

タスク MCP を使用しますか?
Better Auth の初期セットアップ はい - ガイド付き構成
OIDC プロバイダープラグインの追加 はい - 正しい構成を生成します
認証に関する問題のトラブルシューティング はい - セットアップを分析できます
認証フローの理解 はい - 概念を説明します
カスタムミドルウェアの作成 いいえ - 下記のパターンを使用します

アーキテクチャの概要

┌─────────────────┐
│ Better Auth SSO │ ← 中央認証サーバー (auth-server-setup.md)
│  (Auth Server)  │
└────────┬────────┘
         │
    ┌────┴────┐
    ▼         ▼
┌───────┐  ┌───────┐
│ App 1 │  │ App 2 │ ← SSO クライアント (sso-client-integration.md)
└───────┘  └───────┘

クイックスタート: 認証サーバーのセットアップ

npm install better-auth @better-auth/oidc-provider drizzle-orm

コア構成

// src/lib/auth.ts
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { oidcProvider } from "better-auth/plugins/oidc-provider";

export const auth = betterAuth({
  database: drizzleAdapter(db, { provider: "pg", schema }),
  emailAndPassword: { enabled: true },
  session: {
    expiresIn: 60 * 60 * 24 * 7, // 7 days
    updateAge: 60 * 60 * 24,     // 1 day
  },
  plugins: [
    oidcProvider({
      loginPage: "/sign-in",
      consentPage: "/consent",
      // PKCE for public clients (recommended)
      requirePKCE: true,
    }),
  ],
});

OAuth クライアントの登録

// Register SSO client
await auth.api.createOAuthClient({
  name: "My App",
  redirectUris: ["http://localhost:3000/api/auth/callback"],
  type: "public", // Use 'public' for PKCE
});

JWKS、メール検証、および管理ダッシュボードを使用した完全なセットアップについては、references/auth-server-setup.md を参照してください。


クイックスタート: SSO クライアントの統合

npm install jose

環境変数

NEXT_PUBLIC_SSO_URL=http://localhost:3001
NEXT_PUBLIC_SSO_CLIENT_ID=your-client-id

PKCE 認証フロー

// lib/auth-client.ts
import { generateCodeVerifier, generateCodeChallenge } from "./pkce";

export async function startLogin() {
  const verifier = generateCodeVerifier();
  const challenge = await generateCodeChallenge(verifier);

  // Store verifier in cookie
  document.cookie = `pkce_verifier=${verifier}; path=/; SameSite=Lax`;

  const params = new URLSearchParams({
    client_id: process.env.NEXT_PUBLIC_SSO_CLIENT_ID!,
    redirect_uri: `${window.location.origin}/api/auth/callback`,
    response_type: "code",
    scope: "openid profile email",
    code_challenge: challenge,
    code_challenge_method: "S256",
  });

  window.location.href = `${SSO_URL}/oauth2/authorize?${params}`;
}

トークン交換 (API ルート)

// app/api/auth/callback/route.ts
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const code = searchParams.get("code");
  const verifier = cookies().get("pkce_verifier")?.value;

  const response = await fetch(`${SSO_URL}/oauth2/token`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      client_id: process.env.NEXT_PUBLIC_SSO_CLIENT_ID!,
      code: code!,
      redirect_uri: `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/callback`,
      code_verifier: verifier!,
    }),
  });

  const tokens = await response.json();

  // Set httpOnly cookies
  const res = NextResponse.redirect("/dashboard");
  res.cookies.set("access_token", tokens.access_token, { httpOnly: true });
  res.cookies.set("refresh_token", tokens.refresh_token, { httpOnly: true });
  return res;
}

JWKS 検証、トークンリフレッシュ、およびグローバルログアウトについては、references/sso-client-integration.md を参照してください。


PKCE ユーティリティ

// lib/pkce.ts
export function generateCodeVerifier(): string {
  const array = new Uint8Array(32);
  crypto.getRandomValues(array);
  return base64UrlEncode(array);
}

export async function generateCodeChallenge(verifier: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(verifier);
  const hash = await crypto.subtle.digest("SHA-256", data);
  return base64UrlEncode(new Uint8Array(hash));
}

function base64UrlEncode(buffer: Uint8Array): string {
  return btoa(String.fromCharCode(...buffer))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
}

主要なパターン

1. トークンの保存

  • トークンを httpOnly cookies に保存します (localStorage ではありません)。
  • CSRF 保護のために SameSite=Lax を使用します。

2. トークンのリフレッシュ

async function refreshTokens() {
  const response = await fetch(`${SSO_URL}/oauth2/token`, {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "refresh_token",
      client_id: process.env.NEXT_PUBLIC_SSO_CLIENT_ID!,
      refresh_token: currentRefreshToken,
    }),
  });
  return response.json();
}

3. JWKS 検証


import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(
  new URL(`${SSO_URL}/.well-known/jwks.json`)
);

export async function verifyAcc
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Better Auth OAuth/OIDC

Implement centralized authentication with Better Auth - either as an auth server or SSO client.

MCP Server Setup

Better Auth provides an MCP server powered by Chonkie for guided configuration:

claude mcp add --transport http better-auth https://mcp.chonkie.ai/better-auth/better-auth-builder/mcp

Or in settings.json:

{
  "mcpServers": {
    "better-auth": {
      "type": "http",
      "url": "https://mcp.chonkie.ai/better-auth/better-auth-builder/mcp"
    }
  }
}

When to Use the MCP

Task Use MCP?
Initial Better Auth setup Yes - guided configuration
Adding OIDC provider plugin Yes - generates correct config
Troubleshooting auth issues Yes - can analyze setup
Understanding auth flow Yes - explains concepts
Writing custom middleware No - use patterns below

Architecture Overview

┌─────────────────┐
│ Better Auth SSO │ ← Central auth server (auth-server-setup.md)
│  (Auth Server)  │
└────────┬────────┘
         │
    ┌────┴────┐
    ▼         ▼
┌───────┐  ┌───────┐
│ App 1 │  │ App 2 │ ← SSO clients (sso-client-integration.md)
└───────┘  └───────┘

Quick Start: Auth Server Setup

npm install better-auth @better-auth/oidc-provider drizzle-orm

Core Configuration

// src/lib/auth.ts
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { oidcProvider } from "better-auth/plugins/oidc-provider";

export const auth = betterAuth({
  database: drizzleAdapter(db, { provider: "pg", schema }),
  emailAndPassword: { enabled: true },
  session: {
    expiresIn: 60 * 60 * 24 * 7, // 7 days
    updateAge: 60 * 60 * 24,     // 1 day
  },
  plugins: [
    oidcProvider({
      loginPage: "/sign-in",
      consentPage: "/consent",
      // PKCE for public clients (recommended)
      requirePKCE: true,
    }),
  ],
});

Register OAuth Clients

// Register SSO client
await auth.api.createOAuthClient({
  name: "My App",
  redirectUris: ["http://localhost:3000/api/auth/callback"],
  type: "public", // Use 'public' for PKCE
});

See references/auth-server-setup.md for complete setup with JWKS, email verification, and admin dashboard.


Quick Start: SSO Client Integration

npm install jose

Environment Variables

NEXT_PUBLIC_SSO_URL=http://localhost:3001
NEXT_PUBLIC_SSO_CLIENT_ID=your-client-id

PKCE Auth Flow

// lib/auth-client.ts
import { generateCodeVerifier, generateCodeChallenge } from "./pkce";

export async function startLogin() {
  const verifier = generateCodeVerifier();
  const challenge = await generateCodeChallenge(verifier);

  // Store verifier in cookie
  document.cookie = `pkce_verifier=${verifier}; path=/; SameSite=Lax`;

  const params = new URLSearchParams({
    client_id: process.env.NEXT_PUBLIC_SSO_CLIENT_ID!,
    redirect_uri: `${window.location.origin}/api/auth/callback`,
    response_type: "code",
    scope: "openid profile email",
    code_challenge: challenge,
    code_challenge_method: "S256",
  });

  window.location.href = `${SSO_URL}/oauth2/authorize?${params}`;
}

Token Exchange (API Route)

// app/api/auth/callback/route.ts
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const code = searchParams.get("code");
  const verifier = cookies().get("pkce_verifier")?.value;

  const response = await fetch(`${SSO_URL}/oauth2/token`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      client_id: process.env.NEXT_PUBLIC_SSO_CLIENT_ID!,
      code: code!,
      redirect_uri: `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/callback`,
      code_verifier: verifier!,
    }),
  });

  const tokens = await response.json();

  // Set httpOnly cookies
  const res = NextResponse.redirect("/dashboard");
  res.cookies.set("access_token", tokens.access_token, { httpOnly: true });
  res.cookies.set("refresh_token", tokens.refresh_token, { httpOnly: true });
  return res;
}

See references/sso-client-integration.md for JWKS verification, token refresh, and global logout.


PKCE Utilities

// lib/pkce.ts
export function generateCodeVerifier(): string {
  const array = new Uint8Array(32);
  crypto.getRandomValues(array);
  return base64UrlEncode(array);
}

export async function generateCodeChallenge(verifier: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(verifier);
  const hash = await crypto.subtle.digest("SHA-256", data);
  return base64UrlEncode(new Uint8Array(hash));
}

function base64UrlEncode(buffer: Uint8Array): string {
  return btoa(String.fromCharCode(...buffer))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
}

Key Patterns

1. Token Storage

  • Store tokens in httpOnly cookies (not localStorage)
  • Use SameSite=Lax for CSRF protection

2. Token Refresh

async function refreshTokens() {
  const response = await fetch(`${SSO_URL}/oauth2/token`, {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "refresh_token",
      client_id: process.env.NEXT_PUBLIC_SSO_CLIENT_ID!,
      refresh_token: currentRefreshToken,
    }),
  });
  return response.json();
}

3. JWKS Verification

import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(
  new URL(`${SSO_URL}/.well-known/jwks.json`)
);

export async function verifyAccessToken(token: string) {
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: SSO_URL,
    audience: process.env.NEXT_PUBLIC_SSO_CLIENT_ID,
  });
  return payload;
}

4. Global Logout

// Logout from all apps
const logoutUrl = new URL(`${SSO_URL}/oauth2/logout`);
logoutUrl.searchParams.set("post_logout_redirect_uri", window.location.origin);
window.location.href = logoutUrl.toString();

Common Pitfalls

Issue Solution
PKCE verifier lost after redirect Store in httpOnly cookie before redirect
Token in localStorage Use httpOnly cookies instead
JWKS fetch fails Check CORS on auth server
Consent screen loops Ensure consent page saves decision

Verification

Run: python3 scripts/verify.py

Expected: ✓ configuring-better-auth skill ready

If Verification Fails

  1. Check: references/ folder has both setup files
  2. Stop and report if still failing

References

同梱ファイル

※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。