0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Auth0を使用したWebアプリケーションに30分で入門する

Posted at

はじめに

本記事では、Auth0の学習を目的として「Auth0の登録」と「Webアプリ(SPA)の実装」を行います。
今回のゴールは、ローカルで起動したReact Webアプリから Auth0 の Universal Login 画面を経由してログインできるようにすることです。

なお、スクリーンショット他は2025年11月上旬時点の内容です。

Auth0の登録

「無料トライアル」を選択

image.png

GithHubで登録する を選択

image.png

同意する チェックボックスをONにして、登録ボタンをクリック

image.png

GitHubの認証を行う

image.png

Authorize auth0 をクリック

image.png

以上でアカウント作成は完了

**image.png
**

Auth0のアプリケーションの作成

続いてアカウントの設定

個人利用かつ高度な設定は不要として続行します。

image.png

テナントのセットアップが行われます。

image.png

その後、アプリケーションの設定を行います。
今回はSPA用に設定してみます。

アプリケーション名を指定し、「シングルページアプリ」を選択します。

image.png

ユーザーの認証オプションの設定です

image.png

最小構成として、以下を指定します。

  • Database → Username-Password-Authentication
    • ON
  • Social
    • すべてOFF(まずは不要。後で1つずつ追加)

メール/パスワードで動作確認できるので、外部の開発者登録が不要な状態から始めます。

ログイン画面のプレビューが更新されました。
画面上の「アプリケーションの作成」ボタンをクリックします。

image.png

アプリケーションのクイックスタートを進めます。

今回はReactを選択します。

image.png

設定を確認します。
以下の値をアプリのenvファイルに使用します。

  • ドメイン
  • クライアントID

image.png

Auth0のアプリケーションの設定

続いて、WebアプリからAuth0を使用するための設定を行います。

「アプリケーションのURI設定」の以下の箇所にローカル環境で実行するアプリのコールバックURL:http://localhost:5173を設定します

  • 許可するCallback URL
  • 許可するLogout URL
  • 許可するWeb Origins

image.png

以上でAuth0の設定は完了です

Webアプリの準備

この章では、Vite + React + TypeScript で最小の検証用SPAを作成し、Auth0のUniversal Loginでログイン〜ユーザー情報表示までを確認します。

プロジェクト作成

# 任意の作業ディレクトリで
npm create vite@latest auth0-spa -- --template react-ts
cd auth0-spa
npm i

# Auth0 SDK を追加
npm i @auth0/auth0-react

環境変数の設定

ルートに .env を作成し、Auth0のSPA設定画面で確認した「ドメイン」「クライアントID」を記述します。

# .env
VITE_AUTH0_DOMAIN=あなたのテナント.us.auth0.com
VITE_AUTH0_CLIENT_ID=Auth0のSPAクライアントID

# API保護を試す場合のみ(今回は空でOK)
# VITE_AUTH0_AUDIENCE=https://api.example.com

ポイント:

  • まずは VITE_AUTH0_AUDIENCE を設定しない(=空)でOK。APIを使う段階で設定します。
  • .env を変更したら開発サーバーは再起動が必要です。

Auth0Provider を組み込む

src/main.tsx を編集し、アプリ全体を Auth0Provider でラップします。

// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';

const domain = import.meta.env.VITE_AUTH0_DOMAIN as string;
const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID as string;
const audience = import.meta.env.VITE_AUTH0_AUDIENCE as string | undefined;

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      authorizationParams={{
        redirect_uri: window.location.origin,
        ...(audience ? { audience } : {})
      }}
      cacheLocation="localstorage"
      useRefreshTokens
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>
);

最小UI(ログイン/ログアウト/API呼び出し)

src/App.tsx に最小の画面を実装します。

// src/App.tsx
import { useAuth0 } from '@auth0/auth0-react';

export default function App() {
  const { isLoading, isAuthenticated, user, loginWithRedirect, logout, getAccessTokenSilently } = useAuth0();

  const callApi = async () => {
    const token = await getAccessTokenSilently();
    const res = await fetch('/api/private', { headers: { Authorization: `Bearer ${token}` } });
    console.log(await res.json());
  };

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

  return (
    <main style={{ margin: 32, fontFamily: 'system-ui, sans-serif' }}>
      <h1>Auth0 SPA</h1>
      {!isAuthenticated ? (
        <button onClick={() => loginWithRedirect()}>Login</button>
      ) : (
        <>
          <p>Logged in as: {user?.name || user?.email}</p>
          <div style={{ display: 'flex', gap: 12 }}>
            <button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>Logout</button>
            <button onClick={callApi}>Call API</button>
          </div>
          <pre style={{ background: '#f6f8fa', padding: 16, marginTop: 16 }}>{JSON.stringify(user, null, 2)}</pre>
        </>
      )}
    </main>
  );
}

起動

npm run dev

ブラウザで http://localhost:5173 を開きます。

image.png

「Login」ボタンを押すとUniversal Loginに遷移します。
このページでサインアップを行うことで、Auth0側のユーザーが作成されます。

image.png

ログイン成功後はユーザー情報が表示されます。

image.png


まとめ

Auth0の門をくぐるだけなら30分もかからない。

  • 最小構成は「Database接続ON・Social OFF」でOK。Universal Loginでメール/パスワード認証を確認
  • SPA側は Auth0Provider を設定して loginWithRedirect / logout / getAccessTokenSilently を呼べば、基本動作を掴めます
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?