> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Vue アプリケーションにログインを追加する

> このガイドでは、Auth0 Vue SDK を使用して任意の Vue アプリケーションに Auth0 を統合し、認証を追加して、ユーザープロファイル情報を表示する方法を説明します。

> [accordion] AI を使って Auth0 を統合する
>
> Claude Code、Cursor、GitHub Copilot などの AI コーディングアシスタントを使用している場合は、[agent skills](https://agentskills.io/home) を使って数分で Auth0 認証を自動的に追加できます。
>
> **インストール:**
>
> ```bash theme={null}
> npx skills add auth0/agent-skills --skill auth0
> ```
>
> **次に、AI アシスタントに次のように依頼します。**
>
> ```text theme={null}
> Add Auth0 authentication to my Vue app
> ```
>
> AI アシスタントが、Auth0 アプリケーションの作成、資格情報の取得、`@auth0/auth0-vue` のインストール、認証プラグインの作成、ルートの設定を自動的に行います。[agent skills の完全なドキュメント →](/docs/docs/ja-jp/quickstart/agent-skills)

> [!NOTE]
>
> **前提条件:** 始める前に、次のものがインストールされていることを確認してください。
>
> * **[Node.js](https://nodejs.org/en/download)** 20 LTS 以降
> * **[npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)** 10 以降、または **[yarn](https://classic.yarnpkg.com/lang/en/docs/install/)** 1.22 以降、または **[pnpm](https://pnpm.io/installation)** 8 以降
>
> インストールの確認: `node --version && npm --version`
>
> **Vue のバージョン互換性:** この Quickstart は **Vue 3.x** 以降で動作します。

## はじめる

この Quickstart では、Vue.js 3 アプリケーションに Auth0 の認証を統合する方法を紹介します。Vue の Composition API と Auth0 Vue SDK を使用して、安全なユーザー認証を備えたレスポンシブなシングルページアプリケーションを構築します。

**1. 新しいプロジェクトを作成する**

このQuickstart用に新しいVue 3プロジェクトを作成する

```shellscript theme={null}
npm create vue@latest auth0-vue -- --typescript --router --pinia
```

プロジェクトを開く

```shellscript theme={null}
cd auth0-vue
```

**2. Auth0 Vue SDK のインストール**

```shellscript theme={null}
npm add @auth0/auth0-vue && npm install
```

**3. Auth0 Appをセットアップする**

次に、Auth0 テナントに新しいアプリケーションを作成し、環境変数をプロジェクトに追加します。

Auth0 アプリの設定方法は 3 つあります。Quick Setup ツールを使う (推奨) 、CLI コマンドを実行する、または Auth0 Dashboard で手動設定する方法です。

> [tab] クイックセットアップ（推奨）
>
> Auth0 App を作成し、適切な設定値があらかじめ入力された `.env` ファイルをコピーします。

> [tab] CLI
>
> プロジェクトのルートディレクトリで次のコマンドを実行し、Auth0 アプリを作成して `.env` ファイルを生成します。
>
> ```shellscript Mac theme={null}
> # Auth0 CLI をインストールします（まだインストールしていない場合）
> brew tap auth0/auth0-cli && brew install auth0
>
> # Auth0 アプリを設定し、.env ファイルを生成します
> auth0 qs setup --app --type spa --framework vue --build-tool vite --name "My App" --port 5173
> ```
>
> ```powershell Windows theme={null}
> # Auth0 CLI をインストールします（まだインストールしていない場合）
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Auth0 アプリを設定し、.env ファイルを生成します
> auth0 qs setup --app --type spa --framework vue --build-tool vite --name "My App" --port 5173
> ```
>
> > [!NOTE]
> >
> > このコマンドでは次のことが行われます。
> >
> > 1. 認証済みかどうかを確認します (必要に応じてログインを求めます)
> > 2. `http://localhost:5173` 用に設定された Auth0 Single Page Application を作成します
> > 3. `VITE_AUTH0_DOMAIN` と `VITE_AUTH0_CLIENT_ID` を含む `.env` ファイルを生成します

> [tab] Dashboard
>
> 始める前に、プロジェクトのルートディレクトリに `.env` ファイルを作成します。
>
> ```shellscript .env theme={null}
> VITE_AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN
> VITE_AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID
> ```
>
> 1. [Auth0 Dashboard](https://manage.auth0.com/dashboard/) に移動します
> 2. **アプリケーション** > **アプリケーション** > **Create Application** をクリックします
> 3. ポップアップでアプリ名を入力し、アプリの種類として `Single Page Web Application` を選択して **Create** をクリックします
> 4. Application Details ページで **Settings** タブに切り替えます
> 5. `.env` ファイルの `YOUR_AUTH0_APP_DOMAIN` と `YOUR_AUTH0_APP_CLIENT_ID` を、ダッシュボードの **Domain** と **Client ID** の値に置き換えます
>
> 最後に、Application Details ページの **Settings** タブで次の URL を設定します。
>
> **Allowed Callback URLs:**
>
> ```
> http://localhost:5173
> ```
>
> **Allowed Logout URLs:**
>
> ```
> http://localhost:5173
> ```
>
> **Allowed Web Origins:**
>
> ```
> http://localhost:5173
> ```
>
> > [!NOTE]
> >
> > **Allowed Callback URLs** は、認証後にユーザーを安全にアプリケーションへ戻すための重要なセキュリティ対策です。一致する URL がないと、ログイン処理は失敗し、ユーザーはアプリにアクセスできず Auth0 のエラーページが表示されます。
> >
> > **Allowed Logout URLs** は、サインアウト後にシームレスなユーザー体験を提供するために重要です。一致する URL がないと、ユーザーはログアウト後にアプリケーションへリダイレクトされず、代わりに汎用的な Auth0 ページに留まります。
> >
> > **Allowed Web Origins** は、サイレント認証に不可欠です。これがないと、ユーザーはページを再読み込みしたときや、後でアプリに戻ったときにログアウトされます。

> [!TIP]
>
> `.env` ファイルが存在することを確認します: `cat .env` (Mac/Linux) または `type .env` (Windows)

**4. Auth0 プラグインを設定する**

```typescript src/main.ts {6,11,12,13,14,15,16,17} lines theme={null}
import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import router from './router'
import { createAuth0 } from '@auth0/auth0-vue'

import App from './App.vue'

const app = createApp(App)

app.use(createAuth0({
  domain: import.meta.env.VITE_AUTH0_DOMAIN,
  clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
  authorizationParams: {
    redirect_uri: window.location.origin
  }
}))

app.use(createPinia())
app.use(router)

app.mount('#app')
```

**5. 認証コンポーネントを作成**

コンポーネントファイルを作成する

```shellscript Mac/Linux theme={null}
touch src/components/LoginButton.vue && touch src/components/LogoutButton.vue && touch src/components/UserProfile.vue
```

```powershell Windows theme={null}
New-Item -ItemType File -Path src/components/LoginButton.vue
New-Item -ItemType File -Path src/components/LogoutButton.vue
New-Item -ItemType File -Path src/components/UserProfile.vue
```

次のコードスニペットを追加します

**6. アプリを実行する**

```shellscript theme={null}
npm run dev
```

> [!NOTE]
>
> ポート5173が使用中の場合は、`npm run dev -- --port 5174` を実行し、Auth0 App の callback URL を `http://localhost:5174` に更新してください。

> [!TIP]
>
> **チェックポイント**
>
> これで、完全に機能する Auth0 のログインページが [localhost](http://localhost:5173/) 上で正常に動作しているはずです

***

## 高度な使い方

> [accordion] Vue Router でルートを保護する
>
> Vue Router のナビゲーションガードを使って、特定のルートを保護できます。
>
> ```typescript src/router/index.ts theme={null}
> import { createRouter, createWebHistory } from 'vue-router'
> import { authGuard } from '@auth0/auth0-vue'
> import Home from '../views/Home.vue'
> import Profile from '../views/Profile.vue'
> import Dashboard from '../views/Dashboard.vue'
>
> const routes = [
>   {
>     path: '/',
>     name: 'Home',
>     component: Home
>   },
>   {
>     path: '/profile',
>     name: 'Profile',
>     component: Profile,
>     beforeEnter: authGuard
>   },
>   {
>     path: '/dashboard',
>     name: 'Dashboard',
>     component: Dashboard,
>     beforeEnter: authGuard
>   }
> ]
>
> const router = createRouter({
>   history: createWebHistory(),
>   routes
> })
>
> export default router
> ```

> [accordion] 保護された API を呼び出す
>
> API の audience が含まれるように Auth0 Plugin を設定し、認証済みのリクエストを送信します。
>
> ```typescript src/main.ts theme={null}
> import { createAuth0 } from '@auth0/auth0-vue'
>
> const app = createApp(App)
>
> app.use(
>   createAuth0({
>     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"
>     }
>   })
> )
> ```
>
> 次に、コンポーネント内で認証済みの API 呼び出しを行います。
>
> ```vue src/components/ApiCall.vue theme={null}
> <template>
>   <div>
>     <button @click="callProtectedApi" :disabled="isLoading">
>       保護された API を呼び出す
>     </button>
>     <pre v-if="apiResponse">{{ JSON.stringify(apiResponse, null, 2) }}</pre>
>   </div>
> </template>
>
> <script setup lang="ts">
> import { ref } from 'vue'
> import { useAuth0 } from '@auth0/auth0-vue'
>
> const { getAccessTokenSilently } = useAuth0()
> const apiResponse = ref(null)
> const isLoading = ref(false)
>
> const callProtectedApi = async () => {
>   try {
>     isLoading.value = true
>     const token = await getAccessTokenSilently()
>
>     const response = await fetch('/api/protected', {
>       headers: {
>         Authorization: `Bearer ${token}`
>       }
>     })
>
>     apiResponse.value = await response.json()
>   } catch (error) {
>     console.error('API call failed:', error)
>   } finally {
>     isLoading.value = false
>   }
> }
> </script>
> ```

> [accordion] 認証ロジックに Composables を使用する
>
> 一般的な認証パターン向けに、再利用可能な composable を作成します。
>
> ```typescript src/composables/useAuthenticatedUser.ts theme={null}
> import { computed, ref, watchEffect } from 'vue'
> import { useAuth0 } from '@auth0/auth0-vue'
>
> export function useAuthenticatedUser() {
>   const { user, isAuthenticated, isLoading, getAccessTokenSilently } = useAuth0()
>   const accessToken = ref<string | null>(null)
>
>   watchEffect(async () => {
>     if (isAuthenticated.value && !isLoading.value) {
>       try {
>         accessToken.value = await getAccessTokenSilently()
>       } catch (error) {
>         console.error('Failed to get access token:', error)
>       }
>     }
>   })
>
>   return {
>     user: computed(() => user.value),
>     accessToken: computed(() => accessToken.value),
>     isAuthenticated: computed(() => isAuthenticated.value),
>     isLoading: computed(() => isLoading.value)
>   }
> }
> ```
>
> コンポーネントでの使用例:
>
> ```vue src/components/UserDashboard.vue theme={null}
> <template>
>   <div v-if="!isLoading">
>     <h1>ようこそ、{{ user?.name }}</h1>
>     <p>アクセストークン: {{ accessToken ? '利用可能' : '利用不可' }}</p>
>   </div>
>   <div v-else>読み込み中...</div>
> </template>
>
> <script setup lang="ts">
> import { useAuthenticatedUser } from '../composables/useAuthenticatedUser'
>
> const { user, accessToken, isLoading } = useAuthenticatedUser()
> </script>
> ```
