auth0-ionic-react

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Ionic React (Capacitor) Integration

Auth0 Ionic React(Capacitor)集成方案

Add Auth0 authentication to Ionic React applications using Capacitor. This skill covers native mobile authentication using the
@auth0/auth0-react
SDK combined with
@capacitor/browser
and
@capacitor/app
plugins for deep link handling on iOS and Android.
为使用Capacitor的Ionic React应用添加Auth0认证功能。本方案涵盖基于
@auth0/auth0-react
SDK结合
@capacitor/browser
@capacitor/app
插件的移动端原生认证,支持iOS和Android平台的深度链接处理。

Prerequisites

前置条件

  • Node.js 18+
  • Ionic CLI (
    npm install -g @ionic/cli
    )
  • An existing Ionic React 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 React应用
  • 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
React SPA (no Capacitor/Ionic)
auth0-react
React Native (bare CLI)
auth0-react-native
Expo (React Native)
auth0-expo
Ionic + Angular + Capacitor
auth0-ionic-angular
Ionic + Vue + Capacitor
auth0-ionic-vue
Next.js (server-side)
auth0-nextjs
iOS native (Swift)
auth0-swift
Android native (Kotlin)
auth0-android
使用场景推荐方案
React单页应用(无Capacitor/Ionic)
auth0-react
React Native(原生CLI)
auth0-react-native
Expo(React Native)
auth0-expo
Ionic + Angular + Capacitor
auth0-ionic-angular
Ionic + Vue + Capacitor
auth0-ionic-vue
Next.js(服务端)
auth0-nextjs
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和Client ID。

Step 2: Install Dependencies

步骤2:安装依赖

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

Step 3: Set Up Auth0Provider

步骤3:设置Auth0Provider

Wrap the app root with
Auth0Provider
, configuring it for Capacitor. In
src/main.tsx
:
tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';

const domain = import.meta.env.VITE_AUTH0_DOMAIN;
const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID;
const packageId = import.meta.env.VITE_AUTH0_PACKAGE_ID; // e.g., com.example.myapp

const redirectUri = `${packageId}://${domain}/capacitor/${packageId}/callback`;

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      useRefreshTokens={true}
      useRefreshTokensFallback={false}
      authorizationParams={{
        redirect_uri: redirectUri
      }}
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>
);
使用
Auth0Provider
包裹应用根组件,针对Capacitor进行配置。在
src/main.tsx
中:
tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';

const domain = import.meta.env.VITE_AUTH0_DOMAIN;
const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID;
const packageId = import.meta.env.VITE_AUTH0_PACKAGE_ID; // 示例:com.example.myapp

const redirectUri = `${packageId}://${domain}/capacitor/${packageId}/callback`;

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      useRefreshTokens={true}
      useRefreshTokensFallback={false}
      authorizationParams={{
        redirect_uri: redirectUri
      }}
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>
);

Step 4: Implement Login with Capacitor Browser

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

tsx
import { useAuth0 } from '@auth0/auth0-react';
import { Browser } from '@capacitor/browser';

const { loginWithRedirect } = useAuth0();

const login = async () => {
  await loginWithRedirect({
    async openUrl(url) {
      await Browser.open({ url, windowName: "_self" });
    }
  });
};
tsx
import { useAuth0 } from '@auth0/auth0-react';
import { Browser } from '@capacitor/browser';

const { loginWithRedirect } = useAuth0();

const login = async () => {
  await loginWithRedirect({
    async openUrl(url) {
      await Browser.open({ url, windowName: "_self" });
    }
  });
};

Step 5: Handle Callback via Deep Link

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

tsx
import { useEffect } from 'react';
import { App as CapApp } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import { useAuth0 } from '@auth0/auth0-react';

const { handleRedirectCallback } = useAuth0();

useEffect(() => {
  const listener = CapApp.addListener('appUrlOpen', async ({ url }) => {
    if (url.includes('state') && (url.includes('code') || url.includes('error'))) {
      await handleRedirectCallback(url);
    }
    await Browser.close();
  });

  return () => {
    listener.then(l => l.remove());
  };
}, [handleRedirectCallback]);
tsx
import { useEffect } from 'react';
import { App as CapApp } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import { useAuth0 } from '@auth0/auth0-react';

const { handleRedirectCallback } = useAuth0();

useEffect(() => {
  const listener = CapApp.addListener('appUrlOpen', async ({ url }) => {
    if (url.includes('state') && (url.includes('code') || url.includes('error'))) {
      await handleRedirectCallback(url);
    }
    await Browser.close();
  });

  return () => {
    listener.then(l => l.remove());
  };
}, [handleRedirectCallback]);

Step 6: Implement Logout

步骤6:实现登出功能

tsx
const doLogout = async () => {
  await logout({
    logoutParams: {
      returnTo: `${packageId}://${domain}/capacitor/${packageId}/callback`
    },
    async openUrl(url) {
      await Browser.open({ url, windowName: "_self" });
    }
  });
};
tsx
const doLogout = async () => {
  await logout({
    logoutParams: {
      returnTo: `${packageId}://${domain}/capacitor/${packageId}/callback`
    },
    async openUrl(url) {
      await Browser.open({ url, windowName: "_self" });
    }
  });
};

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 configuration, 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 Auth0Provider props, useAuth0 hook, Capacitor plugin configuration, testing checklist, common issues
  • 设置指南 — Auth0 CLI配置、Capacitor URL scheme注册、密钥管理
  • 集成模式 — 基于Capacitor Browser的登录/登出、深度链接回调处理、用户信息、受保护路由、令牌获取、错误处理
  • 测试与参考 — Auth0Provider属性、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}
on Auth0Provider
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
localStorage treated as persistent on mobileUse refresh tokens (
useRefreshTokens={true}
) for reliable token persistence
iOS SSO not workingSFSafariViewController doesn't share cookies with Safari on iOS 11+; this is expected
Not testing on physical deviceAlways test auth flows on a physical device; simulators may not handle deep links correctly
错误修复方案
Auth0控制台中应用类型未设置为Native在控制台设置中将应用类型改为“Native”
回调URL格式缺失或错误使用
YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback
— 必须完全匹配
未启用刷新令牌在Auth0Provider中设置
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
添加到允许的源列表
移动端将localStorage视为持久存储使用刷新令牌(
useRefreshTokens={true}
)实现可靠的令牌持久化
iOS单点登录无法工作iOS 11+中SFSafariViewController与Safari不共享Cookie;此为预期行为
未在物理设备上测试务必在物理设备上测试认证流程;模拟器可能无法正确处理深度链接

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自定义标签页)中打开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-react — React SPA (browser-only, no Capacitor)
  • auth0-ionic-angular — Ionic with Angular and Capacitor
  • auth0-ionic-vue — Ionic with Vue and Capacitor
  • auth0-react-native — React Native (bare CLI, no Ionic/Capacitor)
  • auth0-expo — Expo (React Native) with Auth0
  • auth0-react — React单页应用(仅浏览器端,无Capacitor)
  • auth0-ionic-angular — Ionic + Angular + Capacitor
  • auth0-ionic-vue — Ionic + Vue + Capacitor
  • auth0-react-native — React Native(原生CLI,无Ionic/Capacitor)
  • auth0-expo — Expo(React Native)集成Auth0

Quick Reference

快速参考

APIDescription
Auth0Provider
Context provider — wraps app root with Auth0 config
useAuth0()
Hook — returns
{ isLoading, isAuthenticated, user, loginWithRedirect, logout, getAccessTokenSilently, handleRedirectCallback }
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)
withAuthenticationRequired(Component)
HOC to protect 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描述
Auth0Provider
上下文提供者 — 使用Auth0配置包裹应用根组件
useAuth0()
钩子 — 返回
{ isLoading, isAuthenticated, user, loginWithRedirect, logout, getAccessTokenSilently, handleRedirectCallback }
loginWithRedirect({ openUrl })
通过通用登录实现登录 — 在
openUrl
回调中使用
Browser.open()
logout({ logoutParams, openUrl })
登出功能 — 在
openUrl
回调中使用
Browser.open()
handleRedirectCallback(url)
处理来自深度链接的Auth0回调URL
getAccessTokenSilently()
获取访问令牌(移动端使用刷新令牌)
withAuthenticationRequired(Component)
用于保护路由的高阶组件
Browser.open({ url })
Capacitor API — 在系统浏览器中打开URL(SFSafariViewController / Chrome自定义标签页)
CapApp.addListener('appUrlOpen', cb)
Capacitor API — 监听深度链接事件
Browser.close()
Capacitor API — 回调后关闭内嵌浏览器

References

参考资料