auth0-ionic-react
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 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 SDK combined with and plugins for deep link handling on iOS and Android.
@auth0/auth0-react@capacitor/browser@capacitor/app为使用Capacitor的Ionic React应用添加Auth0认证功能。本方案涵盖基于 SDK结合和插件的移动端原生认证,支持iOS和Android平台的深度链接处理。
@auth0/auth0-react@capacitor/browser@capacitor/appPrerequisites
前置条件
- 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 Case | Recommended Skill |
|---|---|
| React SPA (no Capacitor/Ionic) | |
| React Native (bare CLI) | |
| Expo (React Native) | |
| Ionic + Angular + Capacitor | |
| Ionic + Vue + Capacitor | |
| Next.js (server-side) | |
| iOS native (Swift) | |
| Android native (Kotlin) | |
| 使用场景 | 推荐方案 |
|---|---|
| React单页应用(无Capacitor/Ionic) | |
| React Native(原生CLI) | |
| Expo(React Native) | |
| Ionic + Angular + Capacitor | |
| Ionic + Vue + Capacitor | |
| Next.js(服务端) | |
| iOS原生(Swift) | |
| Android原生(Kotlin) | |
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 syncbash
npm install @auth0/auth0-react @capacitor/browser @capacitor/app
npx cap syncStep 3: Set Up Auth0Provider
步骤3:设置Auth0Provider
Wrap the app root with , configuring it for Capacitor. In :
Auth0Providersrc/main.tsxtsx
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>
);使用包裹应用根组件,针对Capacitor进行配置。在中:
Auth0Providersrc/main.tsxtsx
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:bashionic build npx cap syncFor iOS:then build in Xcode. For Android:npx cap open iosthen build in Android Studio. If the build fails, iterate up to 5-6 times to fix issues. If still failing, usenpx cap open androidto request help.AskUserQuestion
Agent说明:集成完成后,验证构建:bashionic build npx cap synciOS平台:后在Xcode中构建。 Android平台:npx cap open ios后在Android Studio中构建。 若构建失败,可尝试5-6次修复问题。若仍失败,使用npx cap open android请求帮助。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
常见错误
| 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 |
| Not enabling refresh tokens | Set |
Missing | Install both: |
| Not handling deep link callback | Add |
Forgetting | Always run |
Using | Use the custom URL scheme ( |
| Missing Allowed Origins in Dashboard | Add |
| localStorage treated as persistent on mobile | Use refresh tokens ( |
| iOS SSO not working | SFSafariViewController doesn't share cookies with Safari on iOS 11+; this is expected |
| Not testing on physical device | Always test auth flows on a physical device; simulators may not handle deep links correctly |
| 错误 | 修复方案 |
|---|---|
| Auth0控制台中应用类型未设置为Native | 在控制台设置中将应用类型改为“Native” |
| 回调URL格式缺失或错误 | 使用 |
| 未启用刷新令牌 | 在Auth0Provider中设置 |
缺失 | 安装两者: |
| 未处理深度链接回调 | 添加 |
安装后忘记执行 | 安装Capacitor插件后务必执行 |
使用 | 使用自定义URL scheme( |
| 控制台中缺失允许的源 | 将 |
| 移动端将localStorage视为持久存储 | 使用刷新令牌( |
| iOS单点登录无法工作 | iOS 11+中SFSafariViewController与Safari不共享Cookie;此为预期行为 |
| 未在物理设备上测试 | 务必在物理设备上测试认证流程;模拟器可能无法正确处理深度链接 |
WebAuth Method
WebAuth 方法
This SDK uses Auth0's Universal Login (WebAuth) via the Capacitor Browser plugin. The 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: . The plugin captures this deep link, and processes the authorization code exchange.
loginWithRedirect(){packageId}://{domain}/capacitor/{packageId}/callback@capacitor/apphandleRedirectCallback(url)Unlike standard native SDKs that use or , Ionic Capacitor apps use the Capacitor-specific callback path with the package ID as the URL scheme.
https://{domain}/android/{packageId}/callbackhttps://{domain}/ios/{bundleId}/callback本SDK通过Capacitor Browser插件使用Auth0的通用登录(WebAuth)。方法在系统浏览器(iOS为SFSafariViewController,Android为Chrome自定义标签页)中打开Auth0授权端点。认证完成后,Auth0通过带有自定义scheme的原生回调URL重定向回应用:。插件捕获该深度链接,处理授权码交换。
loginWithRedirect(){packageId}://{domain}/capacitor/{packageId}/callback@capacitor/apphandleRedirectCallback(url)与使用或的标准原生SDK不同,Ionic Capacitor应用使用Capacitor专属的回调路径,将包ID作为URL scheme。
https://{domain}/android/{packageId}/callbackhttps://{domain}/ios/{bundleId}/callbackRelated 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
快速参考
| API | Description |
|---|---|
| Context provider — wraps app root with Auth0 config |
| Hook — returns |
| Login via Universal Login — use |
| Logout — use |
| Process Auth0 callback URL from deep link |
| Get access token (uses refresh tokens on mobile) |
| HOC to protect routes |
| Capacitor — opens URL in system browser (SFSafariViewController / Chrome Custom Tabs) |
| Capacitor — listens for deep link events |
| Capacitor — closes the in-app browser after callback |
| API | 描述 |
|---|---|
| 上下文提供者 — 使用Auth0配置包裹应用根组件 |
| 钩子 — 返回 |
| 通过通用登录实现登录 — 在 |
| 登出功能 — 在 |
| 处理来自深度链接的Auth0回调URL |
| 获取访问令牌(移动端使用刷新令牌) |
| 用于保护路由的高阶组件 |
| Capacitor API — 在系统浏览器中打开URL(SFSafariViewController / Chrome自定义标签页) |
| Capacitor API — 监听深度链接事件 |
| Capacitor API — 回调后关闭内嵌浏览器 |