メインコンテンツへスキップ

AI を使って Auth0 を統合する

Claude Code、Cursor、GitHub Copilot などの AI コーディングアシスタントを使用している場合は、agent skills を使って、数分で Auth0 認証を自動的に追加できます。インストール:
npx skills add auth0/agent-skills --skill auth0-quickstart --skill auth0-react
次に、AI アシスタントに次のように依頼します。
Add Auth0 authentication to my React app
AI アシスタントが、Auth0 アプリケーションの作成、認証情報の取得、@auth0/auth0-react のインストール、Auth0Provider の設定、必要なコンポーネントの作成を自動的に行います。agent skills の完全なドキュメント →
前提条件: 開始する前に、次のものがインストールされていることを確認してください。
  • Node.js 20 LTS 以降
  • npm 10 以降、または yarn 1.22 以降、または pnpm 8 以降
インストールを確認するには、次を実行します: node --version && npm --versionReact のバージョン互換性: このクイックスタートは React 18.x 以降に対応しています。

はじめに

このクイックスタートでは、React アプリケーションに Auth0 認証を追加する方法を紹介します。Auth0 React SDK を使用して、ログイン、ログアウト、ユーザープロファイル機能を備えた安全なシングルページアプリケーションを構築します。
1

新しいプロジェクトを作成

このクイックスタート用に新しいReactプロジェクトを作成します
npm create vite@latest auth0-react -- --template react-ts
プロジェクトを開く
cd auth0-react
2

Auth0 React SDKをインストールする

npm add @auth0/auth0-react && npm install
3

Auth0 アプリを設定する

次に、Auth0テナントで新しいアプリを作成し、環境変数をプロジェクトに追加します。Auth0アプリをセットアップする方法は 3 つあります。Quick Setup ツール (推奨) を使う方法、CLI コマンドを実行する方法、または Dashboard で手動設定する方法です。
Auth0アプリを作成し、適切な設定値があらかじめ入力された .env ファイルをコピーします。
.env ファイルが存在することを確認します: cat .env (Mac/Linux) または type .env (Windows)
4

プロバイダーを追加する

src/main.tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css'; // メインCSSファイルのインポート
import App from './App.tsx';
import { Auth0Provider } from '@auth0/auth0-react';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <Auth0Provider
      domain={import.meta.env.VITE_AUTH0_DOMAIN}
      clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
      authorizationParams={{
        redirect_uri: window.location.origin
      }}
    >
      <App />
    </Auth0Provider>
  </StrictMode>
);
5

ログイン、ログアウト、ユーザープロファイルのコンポーネントを作成

ファイルを作成する
touch src/LoginButton.tsx && touch src/LogoutButton.tsx && touch src/Profile.tsx
次のコードスニペットを追加してください
7

アプリを実行する

npm run dev
ポート 5173 が使用中の場合は、npm run dev -- --port 5174 を実行し、Auth0 アプリのコールバック URL を http://localhost:5174 に更新してください
チェックポイントこれで、Auth0 のログインページが localhost 上で完全に動作しているはずです。

高度な使い方

Auth0 の認証状態を使用して、アプリケーション内の特定のルートを保護します。
src/App.jsx
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useAuth0 } from '@auth0/auth0-react';
import Profile from './components/Profile';
import Dashboard from './components/Dashboard';
import LoginButton from './components/LoginButton';

function ProtectedRoute({ children }) {
  const { isAuthenticated, isLoading } = useAuth0();
  
  if (isLoading) return <div>Loading...</div>;
  
  return isAuthenticated ? children : <Navigate to="/" />;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<LoginButton />} />
        <Route 
          path="/profile" 
          element={
            <ProtectedRoute>
              <Profile />
            </ProtectedRoute>
          } 
        />
        <Route 
          path="/dashboard" 
          element={
            <ProtectedRoute>
              <Dashboard />
            </ProtectedRoute>
          } 
        />
      </Routes>
    </BrowserRouter>
  );
}
API のオーディエンスが含まれるように Auth0Provider を設定し、getAccessTokenSilently メソッドを使用します。
src/main.jsx
import { Auth0Provider } from '@auth0/auth0-react';

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <Auth0Provider
    domain={import.meta.env.VITE_AUTH0_DOMAIN}
    clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
    authorizationParams={{
      redirect_uri: window.location.origin,
      audience: "YOUR_API_IDENTIFIER"
    }}
  >
    <App />
  </Auth0Provider>
);
次に、認証済みの API 呼び出しを行います。
src/components/ApiCall.jsx
import { useState } from 'react';
import { useAuth0 } from '@auth0/auth0-react';

function ApiCall() {
  const { getAccessTokenSilently } = useAuth0();
  const [apiResponse, setApiResponse] = useState(null);

  const callProtectedApi = async () => {
    try {
      const token = await getAccessTokenSilently();
      
      const response = await fetch('/api/protected', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      
      const data = await response.json();
      setApiResponse(data);
    } catch (error) {
      console.error('API call failed:', error);
    }
  };

  return (
    <div>
      <button onClick={callProtectedApi}>Call API</button>
      {apiResponse && <pre>{JSON.stringify(apiResponse, null, 2)}</pre>}
    </div>
  );
}

export default ApiCall;
一般的な認証パターン向けに、再利用可能なカスタム Hook を作成します。
src/hooks/useAuthenticatedUser.js
import { useAuth0 } from '@auth0/auth0-react';
import { useEffect, useState } from 'react';

export function useAuthenticatedUser() {
  const { user, isAuthenticated, isLoading, getAccessTokenSilently } = useAuth0();
  const [accessToken, setAccessToken] = useState(null);

  useEffect(() => {
    if (isAuthenticated && !isLoading) {
      getAccessTokenSilently()
        .then(token => setAccessToken(token))
        .catch(console.error);
    }
  }, [isAuthenticated, isLoading, getAccessTokenSilently]);

  return {
    user,
    accessToken,
    isAuthenticated,
    isLoading
  };
}
コンポーネントでの使用例:
src/components/UserDashboard.jsx
import { useAuthenticatedUser } from '../hooks/useAuthenticatedUser';

function UserDashboard() {
  const { user, accessToken, isLoading } = useAuthenticatedUser();

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      <h1>Welcome, {user?.name}</h1>
      <p>Access Token: {accessToken ? 'Available' : 'Not available'}</p>
    </div>
  );
}