claude-skills/

Anthropic公式スキル・プラグインの日本語ディレクトリ

last sync 22h ago
スキルOfficialsecurity

🔐auth0-spa-js

プラグイン
auth0
ライセンス
Apache-2.0

説明

次のような場合に使用: Vanilla JS、Svelte、またはフレームワークに依存しないSPAに、Auth0のログインやトークン管理を追加する場合。 `@auth0/auth0-spa-js` を統合するもので、フレームワーク固有のAuth0 SDKが利用できない場合に使用してください。

原文を表示

Use when adding Auth0 login or token management to a Vanilla JS, Svelte, or framework-agnostic SPA. Integrates @auth0/auth0-spa-js — use when there is no framework-specific Auth0 SDK available.

ユースケース

  • Vanilla JSでAuth0認証を追加するとき
  • Svelteアプリにログイン機能を統合するとき
  • フレームワーク非依存のSPAにトークン管理を追加するとき
  • フレームワーク固有のAuth0 SDKが使えないとき

本文(日本語訳)

Auth0 SPA JS インテグレーション

@auth0/auth0-spa-js を使って、ブラウザベースのシングルページアプリケーション(SPA)に認証機能を追加します。 このSDKは Vanilla JS・Svelte・SolidJS など、React・Angular・Vue 以外のあらゆる SPA 向けの低レベル Auth0 SDK です。

Agent への指示: SDK のセットアップ手順を提供する前に、以下のコマンドを実行して最新リリースバージョンを取得してください:

gh api repos/auth0/auth0-spa-js/releases/latest --jq '.tag_name'

返されたバージョンを、以下に記載されているハードコードされたバージョンの代わりに、すべての依存関係の記述で使用してください。 コマンドが失敗した場合は、https://github.com/auth0/auth0-spa-js/releases を確認してください。

前提条件

  • ES2017+ をサポートするモダンブラウザ
  • npm または yarn(バンドラー不使用のアプリは CDN も可)
  • シングルページアプリケーションとして設定済みの Auth0 アカウント
  • Auth0 の設定がまだの場合は auth0-quickstart を参照

使用すべきでないケース

  • React SPA(hooks・Auth0Provider を使用): auth0-react を使用
  • Angular SPA(AuthModule・AuthGuard を使用): auth0-angular を使用
  • Vue 3 SPA(createAuth0・useAuth0 を使用): auth0-vue を使用
  • Next.js(サーバーサイドセッション・App Router): auth0-nextjs を使用
  • Nuxt(サーバーサイド SSR): auth0-nuxt を使用
  • Express サーバーサイド Web アプリ: auth0-express を使用
  • React Native / Expo モバイルアプリ: auth0-react-native を使用

クイックスタート

1. SDK のインストール

npm install @auth0/auth0-spa-js

または CDN 経由(バンドラー不要)。以下のコマンドで最新バージョンを取得し、HTML で使用します:

VERSION=$(npm view @auth0/auth0-spa-js version)
<script src="https://cdn.auth0.com/js/auth0-spa-js/$VERSION/auth0-spa-js.production.js"></script>

2. Auth0 の設定

Auth0 CLI を使った自動セットアップについては、完全なスクリプトを含む セットアップガイド を参照してください。

手動セットアップの場合は、.env(Vite)を作成します:

VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-id

Auth0 ダッシュボードで、シングルページアプリケーションに対して以下を設定します:

  • Allowed Callback URLs: http://localhost:5173
  • Allowed Logout URLs: http://localhost:5173
  • Allowed Web Origins: http://localhost:5173

3. Auth0 クライアントの初期化

import { createAuth0Client } from '@auth0/auth0-spa-js';

const auth0 = await createAuth0Client({
  domain: import.meta.env.VITE_AUTH0_DOMAIN,
  clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
  authorizationParams: {
    redirect_uri: window.location.origin
  }
});

// ログイン後のリダイレクトコールバックを処理
const query = new URLSearchParams(window.location.search);
if ((query.has('code') || query.has('error')) && query.has('state')) {
  await auth0.handleRedirectCallback();
  window.history.replaceState({}, document.title, window.location.pathname);
}

4. ログイン / ログアウトの追加

Agent への指示: 新しい UI 要素を追加する前に、プロジェクト内にログイン・ログアウト・サインイン・サインアウトボタン用の既存のクリックハンドラーがないか検索してください。 既存のハンドラーが見つかった場合は、既存の UI を変更せずに Auth0 のコードをそこに組み込んでください。 既存のハンドラーが見つからない場合のみ、新しいボタンを作成してください。

// ログイン
document.getElementById('login-btn').addEventListener('click', async () => {
  await auth0.loginWithRedirect();
});

// ログアウト
document.getElementById('logout-btn').addEventListener('click', () => {
  auth0.logout({
    logoutParams: { returnTo: window.location.origin }
  });
});

// 認証状態に応じた UI の更新
const isAuthenticated = await auth0.isAuthenticated();
if (isAuthenticated) {
  const user = await auth0.getUser();
  console.log(user.name, user.email);
}

5. API 呼び出し用アクセストークンの取得

const accessToken = await auth0.getTokenSilently();

const response = await fetch('https://your-api.example.com/data', {
  headers: { Authorization: `Bearer ${accessToken}` }
});

6. ビルドと動作確認

Agent への指示: インテグレーション完了後、以下のコマンドでビルドを実行し、正常にコンパイルされることを確認してください:

npm run build

ビルドが失敗した場合は、エラー出力を分析して問題を修正してください。インテグレーション時によくあるビルドエラーは以下のとおりです:

  • Module not found: npm install @auth0/auth0-spa-js が未実行 — インストールコマンドを実行してください
  • Cannot find name 'import.meta': TypeScript のターゲットが低すぎます — tsconfig.json"target": "ES2020" 以上を設定してください
  • createAuth0Client is not a function: インポートパスが誤っているか、バンドルステップなしで CDN を使用しています
  • 実行時に環境変数が undefined: Vite では VITE_ プレフィックスが必要です。webpack/CRA では REACT_APP_ プレフィックスが必要です

修正のたびにビルドを再実行してください。ビルド修正の試行回数を記録してください。

失敗時の対応: 5〜6 回の修正試行後もビルドが失敗し続ける場合は、作業を中断し、AskUserQuestion を使ってユーザーに確認してください: 「複数回の修正試行後もビルドが失敗しています。どのように進めますか?」

  • Skill に繰り返し修正を続けさせる — さらに 5〜6 回のビルド修正ループを継続する
  • 手動で修正する — 残りのエラーを表示してユーザーに解決してもらう
  • ビルド確認をスキップする — ビルド成功なしで作業を続行する

詳細ドキュメント

  • セットアップガイド — 自動セットアップスクリプト(Bash/PowerShell)・Auth0 CLI コマンド・.env 設定・コールバック URL 設定
  • インテグレーションパターン — トークン管理・API 呼び出し・リフレッシュトークン・Organizations・MFA・DPoP・エラーハンドリング・高度なパターン
  • テストとリファレンス — 設定オプション・クレームリファレンス・テストチェックリスト・よくある問題・セキュリティに関する考慮事項

よくある間違い

間違い 修正方法
コールバック URL のポート番号の不一致(例: localhost:3001 vs localhost:5173 Auth0 ダッシュボードの Allowed Callback URLs を開発サーバーのポート番号に正確に合わせる
SPA のコードに client_secret を含める SPA にクライアントシークレットを含めてはいけません — 削除してください。Auth0 は SPA アプリの認証方式を None に設定します
localStorage へのトークン保存 インメモリストレージ(デフォルト)または sessionStorage を使用してください。localStorage は XSS リスクがあるため使用禁止
ページ更新後に getTokenSilently()login_required をスロー Auth0 ダッシュボードの Allowed Web Origins にアプリのオリジンを追加する
リダイレクト後に handleRedirectCallback() が呼ばれていない ログインリダイレクト後に認証コードを交換するために必ず呼び出す必要があります。呼び出さないと URL パラメータが残り、再トリガーされます
ドメインに https:// プレフィックスを含める Auth0 のドメインはホスト名のみを指定してください: your-tenant.auth0.comhttps://your-tenant.auth0.com は不可)
非同期の初期化コードから loginWithPopup() を呼び出す ポップアップはユーザーの操作(クリックハンドラー)から直接トリガーする必要があります。初期化コードやページロード時には呼び出さないでください
Vanilla JS で @auth0/auth0-reactAuth0Provider を使用する Vanilla JS では createAuth0Client() を直接使用してください — Provider コンポーネントは不要です

関連 Skill

  • auth0-quickstart — Auth0 アカウントとアプリケーションのセットアップ
  • auth0-react — hooks を使った React SPA 向け Auth0
  • auth0-angular — Angular SPA 向け Auth0
  • auth0-vue — Vue 3 SPA 向け Auth0
  • auth0-mfa — 多要素認証(MFA)の追加
  • auth0-cli — ターミナルから Auth0 リソースを管理

クイックリファレンス

コアメソッド

メソッド 説明
createAuth0Client(options) クライアントを作成・初期化する(内部で checkSession を呼び出す)
new Auth0Client(options) セッションの自動チェックなしでインスタンスを生成する
auth0.loginWithRedirect(options?) Auth0 Universal Login へリダイレクトする
auth0.loginWithPopup(options?) ポップアップで Auth0 ログインを開く
auth0.logout(options?) セッションをクリアしてリダイレクトする
auth0.handleRedirectCallback(url?) ログイン後のリダイレクト結果を処理する
auth0.isAuthenticated() Promise<boolean>
auth0.getUser() Promise<User | undefined>
auth0.getTokenSilently(options?) Promise<string> — アクセストークン
auth0.checkSession() サイレント再認証を試みる

よくあるユースケース

参考リンク

原文(English)を表示

Auth0 SPA JS Integration

Add authentication to any browser-based single-page application using @auth0/auth0-spa-js — the low-level Auth0 SDK for Vanilla JS, Svelte, SolidJS, and any SPA not using React, Angular, or Vue.

Agent instruction: Before providing SDK setup instructions, fetch the latest release version by running:

gh api repos/auth0/auth0-spa-js/releases/latest --jq '.tag_name'

Use the returned version in all dependency lines instead of any hardcoded version below. If the command fails, fall back to checking https://github.com/auth0/auth0-spa-js/releases.

Prerequisites

  • Modern browser with ES2017+ support
  • npm or yarn (or use CDN for no-bundler apps)
  • Auth0 account with a Single Page Application configured
  • If you don't have Auth0 set up, see auth0-quickstart

When NOT to Use

Quick Start Workflow

1. Install SDK

npm install @auth0/auth0-spa-js

Or via CDN (no bundler). Run this to get the latest version, then use it in your HTML:

VERSION=$(npm view @auth0/auth0-spa-js version)
<script src="https://cdn.auth0.com/js/auth0-spa-js/$VERSION/auth0-spa-js.production.js"></script>

2. Configure Auth0

For automated setup with Auth0 CLI, see Setup Guide for complete scripts.

For manual setup, create .env (Vite):

VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-id

In Auth0 Dashboard, set for your Single Page Application:

  • Allowed Callback URLs: http://localhost:5173
  • Allowed Logout URLs: http://localhost:5173
  • Allowed Web Origins: http://localhost:5173

3. Initialize Auth0 Client

import { createAuth0Client } from '@auth0/auth0-spa-js';

const auth0 = await createAuth0Client({
  domain: import.meta.env.VITE_AUTH0_DOMAIN,
  clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
  authorizationParams: {
    redirect_uri: window.location.origin
  }
});

// Handle redirect callback after login
const query = new URLSearchParams(window.location.search);
if ((query.has('code') || query.has('error')) && query.has('state')) {
  await auth0.handleRedirectCallback();
  window.history.replaceState({}, document.title, window.location.pathname);
}

4. Add Login / Logout

Agent instruction: Before adding new UI elements, search the project for existing click handlers for login, logout, sign-in, or sign-out buttons. If existing handlers are found, hook the Auth0 code into them without modifying the existing UI. Only create new buttons if no existing handlers are found.

// Login
document.getElementById('login-btn').addEventListener('click', async () => {
  await auth0.loginWithRedirect();
});

// Logout
document.getElementById('logout-btn').addEventListener('click', () => {
  auth0.logout({
    logoutParams: { returnTo: window.location.origin }
  });
});

// Update UI based on auth state
const isAuthenticated = await auth0.isAuthenticated();
if (isAuthenticated) {
  const user = await auth0.getUser();
  console.log(user.name, user.email);
}

5. Get Access Tokens for API Calls

const accessToken = await auth0.getTokenSilently();

const response = await fetch('https://your-api.example.com/data', {
  headers: { Authorization: `Bearer ${accessToken}` }
});

6. Build & Verify

Agent instruction: After completing the integration, build the project to verify it compiles successfully:

npm run build

If the build fails, analyze the error output and fix the issues. Common integration build failures include:

  • Module not found: Missing npm install @auth0/auth0-spa-js — run the install command
  • Cannot find name 'import.meta': TypeScript target too low — set "target": "ES2020" or higher in tsconfig.json
  • createAuth0Client is not a function: Wrong import path or CDN usage without bundle step
  • Env vars undefined at runtime: Vite requires VITE_ prefix; webpack/CRA requires REACT_APP_ prefix

Re-run the build after each fix. Track the number of build-fix iterations.

Failcheck: If the build still fails after 5–6 fix attempts, stop and ask the user using AskUserQuestion: "The build is still failing after several fix attempts. How would you like to proceed?"

  • Let the skill continue fixing iteratively — continue the build-fix loop for another 5–6 attempts
  • Fix it manually — show the remaining errors and let the user resolve them
  • Skip build verification — proceed without a successful build

Detailed Documentation

  • Setup Guide — Automated setup scripts (Bash/PowerShell), Auth0 CLI commands, .env configuration, callback URL setup
  • Integration Patterns — Token management, calling APIs, refresh tokens, organizations, MFA, DPoP, error handling, advanced patterns
  • Testing & Reference — Configuration options, claims reference, testing checklist, common issues, security considerations

Common Mistakes

Mistake Fix
Callback URL port mismatch (e.g., localhost:3001 vs localhost:5173) Match Allowed Callback URLs exactly to your dev server port in Auth0 Dashboard
client_secret in SPA code SPAs must never have a client secret — remove it. Auth0 sets auth method to None for SPA apps
Tokens stored in localStorage Use in-memory storage (default) or sessionStorage. Never localStorage — XSS risk
getTokenSilently() throws login_required on page refresh Add your app origin to Allowed Web Origins in Auth0 Dashboard
handleRedirectCallback() not called after redirect Must call after login redirect to exchange the auth code; without this the URL params persist and re-trigger
Domain includes https:// prefix Auth0 domain should be hostname only: your-tenant.auth0.com, not https://your-tenant.auth0.com
loginWithPopup() called from async init code Popups must be triggered directly from a user gesture (click handler). Never call from init or page load code
Using Auth0Provider from @auth0/auth0-react in Vanilla JS For Vanilla JS, use createAuth0Client() directly — no provider component needed

Related Skills

Quick Reference

Core Methods

Method Description
createAuth0Client(options) Create and initialize client (calls checkSession internally)
new Auth0Client(options) Instantiate without auto session check
auth0.loginWithRedirect(options?) Redirect to Auth0 Universal Login
auth0.loginWithPopup(options?) Open Auth0 login in a popup
auth0.logout(options?) Clear session and redirect
auth0.handleRedirectCallback(url?) Process redirect result after login
auth0.isAuthenticated() Promise<boolean>
auth0.getUser() Promise<User | undefined>
auth0.getTokenSilently(options?) Promise<string> — access token
auth0.checkSession() Attempt silent re-authentication

Common Use Cases

References

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。