auth0-react-native

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 React Native Integration

Auth0 React Native 集成

Add authentication to React Native and Expo mobile applications using react-native-auth0.

为React Native和Expo移动应用添加认证功能,使用react-native-auth0。

Prerequisites

前提条件

  • React Native or Expo application
  • Auth0 account and application configured as Native type
  • If you don't have Auth0 set up yet, use the
    auth0-quickstart
    skill first
  • React Native或Expo应用
  • Auth0账户,且应用已配置为Native类型
  • 若尚未设置Auth0,请先使用
    auth0-quickstart
    技能

When NOT to Use

不适用场景

  • React web applications - Use
    auth0-react
    skill for SPAs (Vite/CRA)
  • React Server Components - Use
    auth0-nextjs
    for Next.js applications
  • Non-React native apps - Use platform-specific SDKs (Swift for iOS, Kotlin for Android)
  • Backend APIs - Use JWT validation libraries for your server language

  • React Web应用 - 针对单页应用(Vite/CRA),请使用
    auth0-react
    技能
  • React Server Components - 针对Next.js应用,请使用
    auth0-nextjs
  • 非React原生应用 - 使用平台专属SDK(iOS用Swift,Android用Kotlin)
  • 后端API - 针对服务端语言,使用JWT验证库

Quick Start Workflow

快速开始流程

1. Install SDK

1. 安装SDK

Expo:
bash
npx expo install react-native-auth0
React Native CLI:
bash
npm install react-native-auth0
npx pod-install  # iOS only
Expo:
bash
npx expo install react-native-auth0
React Native CLI:
bash
npm install react-native-auth0
npx pod-install  # iOS 专属

2. Configure Environment

2. 配置环境

For automated setup with Auth0 CLI, see Setup Guide for complete scripts.
For manual setup:
Create
.env
:
bash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
使用Auth0 CLI自动设置,请查看设置指南获取完整脚本。
手动设置:
创建
.env
文件:
bash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id

3. Configure Native Platforms

3. 配置原生平台

iOS - Update
ios/{YourApp}/Info.plist
:
xml
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleTypeRole</key>
    <string>None</string>
    <key>CFBundleURLName</key>
    <string>auth0</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>$(PRODUCT_BUNDLE_IDENTIFIER).auth0</string>
    </array>
  </dict>
</array>
Android - Update
android/app/src/main/AndroidManifest.xml
:
xml
<activity
    android:name="com.auth0.android.provider.RedirectActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="YOUR_AUTH0_DOMAIN"
            android:pathPrefix="/android/${applicationId}/callback"
            android:scheme="${applicationId}" />
    </intent-filter>
</activity>
Expo - Update
app.json
:
json
{
  "expo": {
    "scheme": "your-app-scheme",
    "ios": {
      "bundleIdentifier": "com.yourcompany.yourapp"
    },
    "android": {
      "package": "com.yourcompany.yourapp"
    }
  }
}
iOS - 更新
ios/{YourApp}/Info.plist
xml
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleTypeRole</key>
    <string>None</string>
    <key>CFBundleURLName</key>
    <string>auth0</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>$(PRODUCT_BUNDLE_IDENTIFIER).auth0</string>
    </array>
  </dict>
</array>
Android - 更新
android/app/src/main/AndroidManifest.xml
xml
<activity
    android:name="com.auth0.android.provider.RedirectActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:host="YOUR_AUTH0_DOMAIN"
            android:pathPrefix="/android/${applicationId}/callback"
            android:scheme="${applicationId}" />
    </intent-filter>
</activity>
Expo - 更新
app.json
json
{
  "expo": {
    "scheme": "your-app-scheme",
    "ios": {
      "bundleIdentifier": "com.yourcompany.yourapp"
    },
    "android": {
      "package": "com.yourcompany.yourapp"
    }
  }
}

4. Add Authentication with Auth0Provider

4. 使用Auth0Provider添加认证

Wrap your app with
Auth0Provider
:
typescript
import React from 'react';
import { Auth0Provider } from 'react-native-auth0';
import App from './App';

export default function Root() {
  return (
    <Auth0Provider
      domain={process.env.AUTH0_DOMAIN}
      clientId={process.env.AUTH0_CLIENT_ID}
    >
      <App />
    </Auth0Provider>
  );
}
Auth0Provider
包裹你的应用:
typescript
import React from 'react';
import { Auth0Provider } from 'react-native-auth0';
import App from './App';

export default function Root() {
  return (
    <Auth0Provider
      domain={process.env.AUTH0_DOMAIN}
      clientId={process.env.AUTH0_CLIENT_ID}
    >
      <App />
    </Auth0Provider>
  );
}

5. Use the useAuth0 Hook

5. 使用useAuth0 Hook

typescript
import React from 'react';
import { View, Button, Text, ActivityIndicator } from 'react-native';
import { useAuth0 } from 'react-native-auth0';

export default function App() {
  const { user, authorize, clearSession, isLoading } = useAuth0();

  const login = async () => {
    try {
      await authorize({
        scope: 'openid profile email'
      });
    } catch (error) {
      console.error('Login error:', error);
    }
  };

  const logout = async () => {
    try {
      await clearSession();
    } catch (error) {
      console.error('Logout error:', error);
    }
  };

  if (isLoading) {
    return <ActivityIndicator />;
  }

  return (
    <View>
      {user ? (
        <>
          <Text>Welcome, {user.name}!</Text>
          <Text>{user.email}</Text>
          <Button title="Logout" onPress={logout} />
        </>
      ) : (
        <Button title="Login" onPress={login} />
      )}
    </View>
  );
}
typescript
import React from 'react';
import { View, Button, Text, ActivityIndicator } from 'react-native';
import { useAuth0 } from 'react-native-auth0';

export default function App() {
  const { user, authorize, clearSession, isLoading } = useAuth0();

  const login = async () => {
    try {
      await authorize({
        scope: 'openid profile email'
      });
    } catch (error) {
      console.error('Login error:', error);
    }
  };

  const logout = async () => {
    try {
      await clearSession();
    } catch (error) {
      console.error('Logout error:', error);
    }
  };

  if (isLoading) {
    return <ActivityIndicator />;
  }

  return (
    <View>
      {user ? (
        <>
          <Text>Welcome, {user.name}!</Text>
          <Text>{user.email}</Text>
          <Button title="Logout" onPress={logout} />
        </>
      ) : (
        <Button title="Login" onPress={login} />
      )}
    </View>
  );
}

6. Test Authentication

6. 测试认证

Expo:
bash
npx expo start
React Native:
bash
npx react-native run-ios
Expo:
bash
npx expo start
React Native:
bash
npx react-native run-ios

or

npx react-native run-android

---
npx react-native run-android

---

Detailed Documentation

详细文档

  • Setup Guide - Automated setup, native configuration, deep linking
  • Patterns Guide - Secure storage, biometric auth, token refresh
  • API Reference - Complete SDK API, methods, configuration options

  • 设置指南 - 自动设置、原生配置、深度链接
  • 模式指南 - 安全存储、生物识别认证、令牌刷新
  • API参考 - 完整SDK API、方法、配置选项

Common Mistakes

常见错误

MistakeFix
Forgot to wrap app with Auth0ProviderAll components using useAuth0() must be children of Auth0Provider
Forgot to configure deep linkingAdd URL scheme to iOS Info.plist and Android AndroidManifest.xml (see Step 3)
Callback URL mismatchEnsure callback URL in Auth0 Dashboard matches your app's URL scheme (e.g.,
com.yourapp.auth0://YOUR_DOMAIN/ios/com.yourapp/callback
)
iOS build fails after installRun
npx pod-install
to link native dependencies
App created as SPA type in Auth0Must be Native application type for mobile apps
Not handling auth errorsWrap authorize/clearSession calls in try-catch blocks
Deep link not working on AndroidVerify
android:exported="true"
is set on RedirectActivity

错误修复方案
忘记用Auth0Provider包裹应用所有使用useAuth0()的组件必须是Auth0Provider的子组件
忘记配置深度链接为iOS Info.plist和Android AndroidManifest.xml添加URL scheme(见步骤3)
回调URL不匹配确保Auth0控制台中的回调URL与应用的URL scheme一致(例如:
com.yourapp.auth0://YOUR_DOMAIN/ios/com.yourapp/callback
安装后iOS构建失败运行
npx pod-install
链接原生依赖
Auth0中应用创建为SPA类型移动应用必须设置为Native应用类型
未处理认证错误将authorize/clearSession调用包裹在try-catch块中
Android上深度链接无法工作验证RedirectActivity已设置
android:exported="true"

Related Skills

相关技能

  • auth0-quickstart
    - Basic Auth0 setup
  • auth0-migration
    - Migrate from another auth provider
  • auth0-mfa
    - Add Multi-Factor Authentication

  • auth0-quickstart
    - Auth0基础设置
  • auth0-migration
    - 从其他认证提供商迁移
  • auth0-mfa
    - 添加多因素认证

Quick Reference

快速参考

Core Hook API:
  • useAuth0()
    - Main hook for authentication
  • authorize()
    - Initiate login
  • clearSession()
    - Logout
  • user
    - User profile object
  • getCredentials()
    - Get tokens for API calls
  • isLoading
    - Loading state
Common Use Cases:
  • Login/Logout → See Step 5 above
  • Secure token storage → Automatic with
    Auth0Provider
  • Biometric authentication → Patterns Guide
  • API calls with tokens → Patterns Guide
  • Token refresh → Automatic with
    getCredentials()

核心Hook API:
  • useAuth0()
    - 主要认证Hook
  • authorize()
    - 发起登录
  • clearSession()
    - 登出
  • user
    - 用户资料对象
  • getCredentials()
    - 获取用于API调用的令牌
  • isLoading
    - 加载状态
常见使用场景:
  • 登录/登出 → 见上方步骤5
  • 安全令牌存储 → 由
    Auth0Provider
    自动处理
  • 生物识别认证 → 模式指南
  • 使用令牌调用API → 模式指南
  • 令牌刷新 → 由
    getCredentials()
    自动处理

References

参考链接