auth0-ionic-vue

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Ionic Vue (Capacitor) Integration

Auth0 Ionic Vue(Capacitor)集成

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.
为使用Capacitor的Ionic Vue应用添加Auth0认证功能。本技能介绍如何结合
@auth0/auth0-vue
SDK与
@capacitor/browser
@capacitor/app
插件,实现iOS和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
  • 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
    安装

When NOT to Use

不适用场景

Use CaseRecommended 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
使用场景推荐技能
Vue单页应用(无Capacitor/Ionic)
auth0-vue
React单页应用(无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

Quick Start Workflow

快速开始流程

Step 1: Configure Auth0

步骤1:配置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.
使用Auth0 CLI自动配置,请查看设置指南获取完整脚本。
手动配置,在Auth0控制台中配置一个Native应用,并记录你的域名(Domain)和客户端ID(Client ID)。

Step 2: Install Dependencies

步骤2:安装依赖

bash
npm install @auth0/auth0-vue @capacitor/browser @capacitor/app
npx cap sync
bash
npm install @auth0/auth0-vue @capacitor/browser @capacitor/app
npx cap sync

Step 3: Set Up Auth0 Plugin

步骤3:设置Auth0插件

Agent instruction: If Step 1 already wrote
.env
and updated
src/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
:
typescript
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');
});
Agent说明: 如果步骤1已生成
.env
并更新
src/main.ts
,请验证配置是否正确,然后跳至步骤4。仅在手动配置时使用以下模板。
在应用入口文件
src/main.ts
中注册Auth0 Vue插件,并针对Capacitor进行配置。通过
import.meta.env
.env
读取凭证:
typescript
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');
});

Step 4: Implement Login with Capacitor Browser

步骤4:通过Capacitor Browser实现登录

vue
<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>
vue
<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">登录</ion-button>
</template>

Step 5: Handle Callback via Deep Link

步骤5:通过深度链接处理回调

Handle the deep link callback in your App.vue component. This must run on app initialization:
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>
在App.vue组件中处理深度链接回调,此逻辑必须在应用初始化时运行:
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>

Step 6: Implement Logout

步骤6:实现登出功能

vue
<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>
vue
<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">登出</ion-button>
</template>

Step 7: Build and Test

步骤7:构建并测试

Agent instruction: After integration, verify the build:
bash
ionic build
npx cap sync
For iOS:
npx cap open ios
then build in Xcode. For Android:
npx cap open android
then build in Android Studio. If the build fails, iterate up to 5-6 times to fix issues. If still failing, use
AskUserQuestion
to request help.
Agent说明: 集成完成后,验证构建:
bash
ionic build
npx cap sync
iOS平台:执行
npx cap open ios
后在Xcode中构建。 Android平台:执行
npx cap open android
后在Android Studio中构建。 如果构建失败,可尝试修复5-6次。若仍失败,使用
AskUserQuestion
请求帮助。

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
  • 设置指南 — Auth0 CLI自动配置(登录、应用创建、凭证注入)、Capacitor URL scheme注册、密钥管理
  • 集成模式 — 基于Capacitor Browser的登录/登出、深度链接回调处理、用户信息、受保护路由、令牌访问、错误处理
  • 测试与参考 — createAuth0选项、useAuth0组合式函数、Capacitor插件配置的完整API参考、测试清单、常见问题

Common Mistakes

常见错误

MistakeFix
App type not set to Native in Auth0 DashboardChange application type to "Native" in Dashboard settings
Missing or incorrect callback URL formatUse
YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback
— must match exactly
Not enabling refresh tokensSet
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 callbackAdd
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 DashboardAdd
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 mobileUse refresh tokens (
useRefreshTokens: true
) for reliable token persistence
错误修复方案
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
使用
window.location.origin
作为重定向URI
使用自定义URL scheme(
packageId://domain/...
),而非
http://localhost
控制台中缺少允许的源
capacitor://localhost, http://localhost
添加至允许的源列表
在挂载前未调用
app.use(createAuth0(...))
在调用
app.mount('#app')
之前注册Auth0插件
错误地访问auth引用的
.value
useAuth0()
返回Vue引用 — 在
<script>
中使用
.value
,模板会自动解包
将localStorage视为移动端持久存储使用刷新令牌(
useRefreshTokens: true
)实现可靠的令牌持久化

WebAuth Method

WebAuth方法

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.
本SDK通过Capacitor Browser插件使用Auth0的通用登录(WebAuth)。
loginWithRedirect()
方法在系统浏览器(iOS为SFSafariViewController,Android为Chrome Custom Tabs)中打开Auth0授权端点。认证完成后,Auth0通过带有自定义scheme的原生回调URL重定向回应用:
{packageId}://{domain}/capacitor/{packageId}/callback
@capacitor/app
插件捕获此深度链接,
handleRedirectCallback(url)
处理授权码交换。
与使用
https://{domain}/android/{packageId}/callback
https://{domain}/ios/{bundleId}/callback
的标准原生SDK不同,Ionic Capacitor应用使用Capacitor专属的回调路径,以包ID作为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
  • auth0-vue — Vue单页应用(仅浏览器端,无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

Quick Reference

快速参考

APIDescription
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
API描述
createAuth0(options)
Vue插件工厂 — 通过
app.use()
注册Auth0
useAuth0()
组合式函数 — 返回
{ isLoading, isAuthenticated, user, loginWithRedirect, logout, getAccessTokenSilently, handleRedirectCallback, error }
loginWithRedirect({ openUrl })
通过通用登录实现登录 — 在
openUrl
回调中使用
Browser.open()
logout({ logoutParams, openUrl })
登出 — 在
openUrl
回调中使用
Browser.open()
handleRedirectCallback(url)
处理来自深度链接的Auth0回调URL
getAccessTokenSilently()
获取访问令牌(移动端使用刷新令牌)
createAuthGuard(app)
Vue Router导航守卫工厂,用于受保护路由
Browser.open({ url })
Capacitor — 在系统浏览器中打开URL(SFSafariViewController / Chrome Custom Tabs)
CapApp.addListener('appUrlOpen', cb)
Capacitor — 监听深度链接事件
Browser.close()
Capacitor — 回调后关闭内嵌浏览器

References

参考链接