🔐auth0-ionic-vue
- プラグイン
- auth0
- ライセンス
- Apache-2.0
- ソース
- GitHub で見る ↗
説明
次のような場合に使用: Capacitorを使用したIonic VueアプリにAuth0のログイン・ログアウト、またはディープリンクを追加する場合。 ネイティブのiOS/Android向けに、Capacitor BrowserおよびApp pluginと`@auth0/auth0-vue`を統合します。
原文を表示
Use when adding Auth0 login, logout, or deep linking to an Ionic Vue app with Capacitor. Integrates @auth0/auth0-vue with Capacitor Browser and App plugins for native iOS/Android.
ユースケース
- ✓Ionic VueアプリにAuth0ログインを追加するとき
- ✓Ionic VueアプリにAuth0ログアウトを追加するとき
- ✓Ionic Vueアプリにディープリンクを追加するとき
- ✓ネイティブiOS/Android向けAuth0認証を実装するとき
本文(日本語訳)
Auth0 Ionic Vue(Capacitor)インテグレーション
Capacitor を使用した Ionic Vue アプリケーションに Auth0 認証を追加します。
このスキルは、iOS および Android でのディープリンク処理のために @capacitor/browser と @capacitor/app プラグインを組み合わせた @auth0/auth0-vue SDK を使用した、ネイティブモバイル認証を対象としています。
前提条件
- Node.js 18 以上
- Ionic CLI(
npm install -g @ionic/cli) - Capacitor が設定済みの既存の Ionic Vue アプリケーション
- Auth0 アカウントおよびテナント
- iOS の場合: Xcode 14 以上、および CocoaPods
- Android の場合: API レベル 21 以上の Android Studio
- Auth0 CLI —
brew install auth0/auth0-cli/auth0
使用しない場面
| ユースケース | 推奨スキル |
|---|---|
| Vue SPA(Capacitor/Ionic なし) | auth0-vue |
| React SPA(Capacitor/Ionic なし) | auth0-react |
| React Native(ベア CLI) | auth0-react-native |
| Expo(React Native) | auth0-expo |
| Ionic + React + Capacitor | auth0-ionic-react |
| Ionic + Angular + Capacitor | auth0-ionic-angular |
| Next.js(サーバーサイド) | auth0-nextjs |
| Nuxt(サーバーサイド) | auth0-nuxt |
| iOS ネイティブ(Swift) | auth0-swift |
| Android ネイティブ(Kotlin) | auth0-android |
クイックスタート手順
ステップ 1: Auth0 の設定
Auth0 CLI を使った自動セットアップについては、完全なスクリプトを セットアップガイド で確認してください。
手動セットアップの場合は、Auth0 ダッシュボード で Native アプリケーションを設定し、Domain と Client ID を控えておきます。
ステップ 2: 依存関係のインストール
npm install @auth0/auth0-vue @capacitor/browser @capacitor/app
npx cap sync
ステップ 3: Auth0 プラグインのセットアップ
Agent への指示: ステップ 1 で既に
.envの書き込みとsrc/main.tsの更新が完了している場合は、設定内容が正しいことを確認してステップ 4 に進んでください。以下のテンプレートは手動設定の場合にのみ使用します。
アプリのエントリーポイント(src/main.ts)に Auth0 Vue プラグインを登録し、Capacitor 向けに設定します。
認証情報は import.meta.env を通じて .env から読み込まれます。
import { createApp } from 'vue';
import { createAuth0 } from '@auth0/auth0-vue';
import { IonicVue } from '@ionic/vue';
import App from './App.vue';
import router from './router';
// Agent: capacitor.config.ts から appId を読み取り、この値を置き換えてください
const packageId = "YOUR_PACKAGE_ID";
const app = createApp(App);
app.use(IonicVue);
app.use(router);
app.use(
createAuth0({
domain: import.meta.env.VITE_AUTH0_DOMAIN,
clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
useRefreshTokens: true,
useRefreshTokensFallback: false,
authorizationParams: {
redirect_uri: `${packageId}://${import.meta.env.VITE_AUTH0_DOMAIN}/capacitor/${packageId}/callback`
}
})
);
router.isReady().then(() => {
app.mount('#app');
});
ステップ 4: Capacitor Browser を使ったログインの実装
<script setup lang="ts">
import { useAuth0 } from '@auth0/auth0-vue';
import { Browser } from '@capacitor/browser';
import { IonButton } from '@ionic/vue';
const { loginWithRedirect } = useAuth0();
const login = async () => {
await loginWithRedirect({
async openUrl(url: string) {
await Browser.open({ url, windowName: "_self" });
}
});
};
</script>
<template>
<ion-button @click="login">Log in</ion-button>
</template>
ステップ 5: ディープリンクによるコールバック処理
App.vue コンポーネントでディープリンクのコールバックを処理します。 この処理はアプリの初期化時に実行される必要があります。
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue';
import { useAuth0 } from '@auth0/auth0-vue';
import { App as CapApp } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import { IonApp, IonRouterOutlet } from '@ionic/vue';
const { handleRedirectCallback } = useAuth0();
let urlOpenListener: any;
onMounted(async () => {
urlOpenListener = await CapApp.addListener('appUrlOpen', async ({ url }) => {
if (url.includes('state') && (url.includes('code') || url.includes('error'))) {
await handleRedirectCallback(url);
}
await Browser.close();
});
});
onUnmounted(() => {
urlOpenListener?.remove();
});
</script>
<template>
<ion-app>
<ion-router-outlet />
</ion-app>
</template>
ステップ 6: ログアウトの実装
<script setup lang="ts">
import { useAuth0 } from '@auth0/auth0-vue';
import { Browser } from '@capacitor/browser';
import { IonButton } from '@ionic/vue';
const domain = import.meta.env.VITE_AUTH0_DOMAIN;
// Agent: capacitor.config.ts から appId を読み取り、この値を置き換えてください
const packageId = "YOUR_PACKAGE_ID";
const logoutUri = `${packageId}://${domain}/capacitor/${packageId}/callback`;
const { logout } = useAuth0();
const doLogout = async () => {
await logout({
logoutParams: {
returnTo: logoutUri
},
async openUrl(url: string) {
await Browser.open({ url, windowName: "_self" });
}
});
};
</script>
<template>
<ion-button @click="doLogout">Log out</ion-button>
</template>
ステップ 7: ビルドとテスト
Agent への指示: インテグレーション完了後、以下のコマンドでビルドを確認してください:
ionic build npx cap synciOS の場合:
npx cap open iosを実行後、Xcode でビルドします。 Android の場合:npx cap open androidを実行後、Android Studio でビルドします。 ビルドが失敗した場合は、5〜6 回繰り返して問題を修正してください。それでも解決しない場合は、AskUserQuestionを使用してサポートを依頼してください。
詳細ドキュメント
- セットアップガイド — Auth0 CLI による自動セットアップ(ログイン、アプリ作成、認証情報の注入)、Capacitor URL スキームの登録、シークレット管理
- インテグレーションパターン — Capacitor Browser を使ったログイン/ログアウト、ディープリンクコールバックの処理、ユーザープロファイル、保護されたルート、トークンアクセス、エラーハンドリング
- テスト&リファレンス —
createAuth0オプション、useAuth0コンポーザブル、Capacitor プラグイン設定の完全な API リファレンス、テストチェックリスト、よくある問題
よくある間違い
| 間違い | 修正方法 |
|---|---|
| Auth0 ダッシュボードでアプリケーションタイプが Native に設定されていない | ダッシュボードの設定でアプリケーションタイプを "Native" に変更する |
| コールバック URL の形式が不正または誤っている | YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback の形式を使用し、完全に一致させること |
| リフレッシュトークンが有効化されていない | createAuth0() に useRefreshTokens: true と useRefreshTokensFallback: false を設定する |
@capacitor/browser または @capacitor/app がインストールされていない |
両方をインストールする: npm install @capacitor/browser @capacitor/app && npx cap sync |
| ディープリンクコールバックが処理されていない | CapApp.addListener('appUrlOpen', ...) を追加して Auth0 リダイレクトを処理する |
インストール後に npx cap sync を忘れる |
Capacitor プラグインのインストール後は必ず npx cap sync を実行する |
リダイレクト URI に window.location.origin を使用している |
http://localhost ではなく、カスタム URL スキーム(packageId://domain/...)を使用する |
| ダッシュボードで Allowed Origins が設定されていない | Allowed Origins に capacitor://localhost, http://localhost を追加する |
マウント前に app.use(createAuth0(...)) を呼び出していない |
app.mount('#app') を呼び出す前に Auth0 プラグインを登録する |
auth の ref に対して .value を誤って使用している |
useAuth0() は Vue の ref を返す — <script> 内では .value を使用し、テンプレート内では自動的にアンラップされる |
| モバイルで localStorage が永続的だと思い込んでいる | 信頼性の高いトークン永続化のためにリフレッシュトークン(useRefreshTokens: true)を使用する |
WebAuth メソッド
この SDK は、Capacitor Browser プラグインを介して Auth0 の Universal Login(WebAuth)を使用します。
loginWithRedirect() メソッドは、Auth0 の認可エンドポイントをシステムブラウザ(iOS では SFSafariViewController、Android では Chrome Custom Tabs)で開きます。
認証後、Auth0 はカスタムスキームを使ったネイティブコールバック URL({packageId}://{domain}/capacitor/{packageId}/callback)を通じてアプリにリダイレクトします。
@capacitor/app プラグインがこのディープリンクを捕捉し、handleRedirectCallback(url) が認可コードの交換処理を行います。
https://{domain}/android/{packageId}/callback や https://{domain}/ios/{bundleId}/callback を使用する標準的なネイティブ SDK とは異なり、Ionic Capacitor アプリでは URL スキームとしてパッケージ ID を使った Capacitor 固有のコールバックパスを使用します。
関連スキル
- auth0-vue — Vue SPA(ブラウザのみ、Capacitor なし)
- auth0-ionic-react — Ionic + React + Capacitor
- auth0-ionic-angular — Ionic + Angular + Capacitor
- auth0-react-native — React Native(ベア CLI、Ionic/Capacitor なし)
- auth0-expo — Expo(React Native)と Auth0
クイックリファレンス
| API | 説明 |
|---|---|
createAuth0(options) |
Vue プラグインファクトリー — app.use() で Auth0 を登録する |
useAuth0() |
コンポーザブル — { isLoading, isAuthenticated, user, loginWithRedirect, logout, getAccessTokenSilently, handleRedirectCallback, error } を返す |
loginWithRedirect({ openUrl }) |
Universal Login 経由でログイン — openUrl コールバック内で Browser.open() を使用する |
logout({ logoutParams, openUrl }) |
ログアウト — openUrl コールバック内で Browser.open() を使用する |
handleRedirectCallback(url) |
ディープリンクから Auth0 コールバック URL を処理する |
getAccessTokenSilently() |
アクセストークンを取得する(モバイルではリフレッシュトークンを使用) |
createAuthGuard(app) |
保護されたルート向けの Vue Router ナビゲーションガードファクトリー |
Browser.open({ url }) |
Capacitor — システムブラウザ(SFSafariViewController / Chrome Custom Tabs)で URL を開く |
CapApp.addListener('appUrlOpen', cb) |
Capacitor — ディープリンクイベントをリッスンする |
Browser.close() |
Capacitor — コールバック後にインアプリブラウザを閉じる |
参考リンク
原文(English)を表示
Auth0 Ionic Vue (Capacitor) Integration
Add Auth0 authentication to Ionic Vue applications using Capacitor. This skill covers native mobile authentication using the @auth0/auth0-vue SDK combined with @capacitor/browser and @capacitor/app plugins for deep link handling on iOS and Android.
Prerequisites
- Node.js 18+
- Ionic CLI (
npm install -g @ionic/cli) - An existing Ionic Vue application with Capacitor configured
- Auth0 account and tenant
- For iOS: Xcode 14+ and CocoaPods
- For Android: Android Studio with API level 21+
- Auth0 CLI —
brew install auth0/auth0-cli/auth0
When NOT to Use
| Use Case | Recommended Skill |
|---|---|
| Vue SPA (no Capacitor/Ionic) | auth0-vue |
| React SPA (no Capacitor/Ionic) | auth0-react |
| React Native (bare CLI) | auth0-react-native |
| Expo (React Native) | auth0-expo |
| Ionic + React + Capacitor | auth0-ionic-react |
| Ionic + Angular + Capacitor | auth0-ionic-angular |
| Next.js (server-side) | auth0-nextjs |
| Nuxt (server-side) | auth0-nuxt |
| iOS native (Swift) | auth0-swift |
| Android native (Kotlin) | auth0-android |
Quick Start Workflow
Step 1: Configure Auth0
For automated setup with Auth0 CLI, see Setup Guide for complete scripts.
For manual setup, configure a Native application in the Auth0 Dashboard and note your Domain and Client ID.
Step 2: Install Dependencies
npm install @auth0/auth0-vue @capacitor/browser @capacitor/app
npx cap sync
Step 3: Set Up Auth0 Plugin
Agent instruction: If Step 1 already wrote
.envand updatedsrc/main.ts, verify the configuration looks correct and skip to Step 4. Only use the template below if configuring manually.
Register the Auth0 Vue plugin in your app entry point (src/main.ts), configuring it for Capacitor. Credentials are read from .env via import.meta.env:
import { createApp } from 'vue';
import { createAuth0 } from '@auth0/auth0-vue';
import { IonicVue } from '@ionic/vue';
import App from './App.vue';
import router from './router';
// Agent: read appId from capacitor.config.ts and replace this value
const packageId = "YOUR_PACKAGE_ID";
const app = createApp(App);
app.use(IonicVue);
app.use(router);
app.use(
createAuth0({
domain: import.meta.env.VITE_AUTH0_DOMAIN,
clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
useRefreshTokens: true,
useRefreshTokensFallback: false,
authorizationParams: {
redirect_uri: `${packageId}://${import.meta.env.VITE_AUTH0_DOMAIN}/capacitor/${packageId}/callback`
}
})
);
router.isReady().then(() => {
app.mount('#app');
});
Step 4: Implement Login with Capacitor Browser
<script setup lang="ts">
import { useAuth0 } from '@auth0/auth0-vue';
import { Browser } from '@capacitor/browser';
import { IonButton } from '@ionic/vue';
const { loginWithRedirect } = useAuth0();
const login = async () => {
await loginWithRedirect({
async openUrl(url: string) {
await Browser.open({ url, windowName: "_self" });
}
});
};
</script>
<template>
<ion-button @click="login">Log in</ion-button>
</template>
Step 5: Handle Callback via Deep Link
Handle the deep link callback in your App.vue component. This must run on app initialization:
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue';
import { useAuth0 } from '@auth0/auth0-vue';
import { App as CapApp } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import { IonApp, IonRouterOutlet } from '@ionic/vue';
const { handleRedirectCallback } = useAuth0();
let urlOpenListener: any;
onMounted(async () => {
urlOpenListener = await CapApp.addListener('appUrlOpen', async ({ url }) => {
if (url.includes('state') && (url.includes('code') || url.includes('error'))) {
await handleRedirectCallback(url);
}
await Browser.close();
});
});
onUnmounted(() => {
urlOpenListener?.remove();
});
</script>
<template>
<ion-app>
<ion-router-outlet />
</ion-app>
</template>
Step 6: Implement Logout
<script setup lang="ts">
import { useAuth0 } from '@auth0/auth0-vue';
import { Browser } from '@capacitor/browser';
import { IonButton } from '@ionic/vue';
const domain = import.meta.env.VITE_AUTH0_DOMAIN;
// Agent: read appId from capacitor.config.ts and replace this value
const packageId = "YOUR_PACKAGE_ID";
const logoutUri = `${packageId}://${domain}/capacitor/${packageId}/callback`;
const { logout } = useAuth0();
const doLogout = async () => {
await logout({
logoutParams: {
returnTo: logoutUri
},
async openUrl(url: string) {
await Browser.open({ url, windowName: "_self" });
}
});
};
</script>
<template>
<ion-button @click="doLogout">Log out</ion-button>
</template>
Step 7: Build and Test
Agent instruction: After integration, verify the build:
ionic build npx cap syncFor iOS:
npx cap open iosthen build in Xcode. For Android:npx cap open androidthen build in Android Studio. If the build fails, iterate up to 5-6 times to fix issues. If still failing, useAskUserQuestionto request help.
Detailed Documentation
- Setup Guide — Auth0 CLI automated setup (login, app creation, credential injection), Capacitor URL scheme registration, secret management
- Integration Patterns — Login/logout with Capacitor Browser, deep link callback handling, user profile, protected routes, token access, error handling
- Testing & Reference — Full API reference for createAuth0 options, useAuth0 composable, Capacitor plugin configuration, testing checklist, common issues
Common Mistakes
| Mistake | Fix |
|---|---|
| App type not set to Native in Auth0 Dashboard | Change application type to "Native" in Dashboard settings |
| Missing or incorrect callback URL format | Use YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback — must match exactly |
| Not enabling refresh tokens | Set useRefreshTokens: true and useRefreshTokensFallback: false in createAuth0() |
Missing @capacitor/browser or @capacitor/app |
Install both: npm install @capacitor/browser @capacitor/app && npx cap sync |
| Not handling deep link callback | Add CapApp.addListener('appUrlOpen', ...) to process Auth0 redirect |
Forgetting npx cap sync after install |
Always run npx cap sync after installing Capacitor plugins |
Using window.location.origin as redirect URI |
Use the custom URL scheme (packageId://domain/...), not http://localhost |
| Missing Allowed Origins in Dashboard | Add capacitor://localhost, http://localhost to Allowed Origins |
Not calling app.use(createAuth0(...)) before mount |
Register Auth0 plugin before calling app.mount('#app') |
Accessing .value incorrectly on auth refs |
useAuth0() returns Vue refs — use .value in <script>, template unwraps automatically |
| localStorage treated as persistent on mobile | Use refresh tokens (useRefreshTokens: true) for reliable token persistence |
WebAuth Method
This SDK uses Auth0's Universal Login (WebAuth) via the Capacitor Browser plugin. The loginWithRedirect() method opens the Auth0 authorization endpoint in a system browser (SFSafariViewController on iOS, Chrome Custom Tabs on Android). After authentication, Auth0 redirects back to the app using a native callback URL with a custom scheme: {packageId}://{domain}/capacitor/{packageId}/callback. The @capacitor/app plugin captures this deep link, and handleRedirectCallback(url) processes the authorization code exchange.
Unlike standard native SDKs that use https://{domain}/android/{packageId}/callback or https://{domain}/ios/{bundleId}/callback, Ionic Capacitor apps use the Capacitor-specific callback path with the package ID as the URL scheme.
Related Skills
- auth0-vue — Vue SPA (browser-only, no Capacitor)
- auth0-ionic-react — Ionic with React and Capacitor
- auth0-ionic-angular — Ionic with Angular and Capacitor
- auth0-react-native — React Native (bare CLI, no Ionic/Capacitor)
- auth0-expo — Expo (React Native) with Auth0
Quick Reference
| API | Description |
|---|---|
createAuth0(options) |
Vue plugin factory — registers Auth0 with app.use() |
useAuth0() |
Composable — returns { isLoading, isAuthenticated, user, loginWithRedirect, logout, getAccessTokenSilently, handleRedirectCallback, error } |
loginWithRedirect({ openUrl }) |
Login via Universal Login — use Browser.open() in openUrl callback |
logout({ logoutParams, openUrl }) |
Logout — use Browser.open() in openUrl callback |
handleRedirectCallback(url) |
Process Auth0 callback URL from deep link |
getAccessTokenSilently() |
Get access token (uses refresh tokens on mobile) |
createAuthGuard(app) |
Vue Router navigation guard factory for protected routes |
Browser.open({ url }) |
Capacitor — opens URL in system browser (SFSafariViewController / Chrome Custom Tabs) |
CapApp.addListener('appUrlOpen', cb) |
Capacitor — listens for deep link events |
Browser.close() |
Capacitor — closes the in-app browser after callback |
References
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。