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

AI を使って Auth0 を統合する

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

はじめに

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

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

このクイックスタート用に新しい Vue 3 プロジェクトを作成する
npm create vue@latest auth0-vue -- --typescript --router --pinia
プロジェクトを開く
cd auth0-vue
2

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

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

Auth0アプリを設定する

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

Auth0 プラグインを構成する

src/main.ts
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

認証コンポーネントを作成

コンポーネントファイルを作成する
touch src/components/LoginButton.vue && touch src/components/LogoutButton.vue && touch src/components/UserProfile.vue
次のコードスニペットを追加してください
6

アプリを実行する

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

高度な使い方

Vue Router のナビゲーションガードを使用して、特定のルートを保護します。
src/router/index.ts
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
API のオーディエンスが含まれるように Auth0 プラグインを設定し、認証済みリクエストを送信します。
src/main.ts
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 呼び出しを行います。
src/components/ApiCall.vue
<template>
  <div>
    <button @click="callProtectedApi" :disabled="isLoading">
      Call Protected 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>
一般的な認証パターン向けに、再利用可能な composable を作成します。
src/composables/useAuthenticatedUser.ts
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)
  }
}
コンポーネントでの使用例:
src/components/UserDashboard.vue
<template>
  <div v-if="!isLoading">
    <h1>Welcome, {{ user?.name }}</h1>
    <p>Access Token: {{ accessToken ? 'Available' : 'Not available' }}</p>
  </div>
  <div v-else>Loading...</div>
</template>

<script setup lang="ts">
import { useAuthenticatedUser } from '../composables/useAuthenticatedUser'

const { user, accessToken, isLoading } = useAuthenticatedUser()
</script>