auth0-react-native
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 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 skill first
auth0-quickstart
- React Native或Expo应用
- Auth0账户,且应用已配置为Native类型
- 若尚未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用场景
- React web applications - Use skill for SPAs (Vite/CRA)
auth0-react - React Server Components - Use for Next.js applications
auth0-nextjs - 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-auth0React Native CLI:
bash
npm install react-native-auth0
npx pod-install # iOS onlyExpo:
bash
npx expo install react-native-auth0React 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 :
.envbash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id使用Auth0 CLI自动设置,请查看设置指南获取完整脚本。
手动设置:
创建文件:
.envbash
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id3. Configure Native Platforms
3. 配置原生平台
iOS - Update :
ios/{YourApp}/Info.plistxml
<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.xmlxml
<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.jsonjson
{
"expo": {
"scheme": "your-app-scheme",
"ios": {
"bundleIdentifier": "com.yourcompany.yourapp"
},
"android": {
"package": "com.yourcompany.yourapp"
}
}
}iOS - 更新:
ios/{YourApp}/Info.plistxml
<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.xmlxml
<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.jsonjson
{
"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 :
Auth0Providertypescript
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>
);
}用包裹你的应用:
Auth0Providertypescript
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 startReact Native:
bash
npx react-native run-iosExpo:
bash
npx expo startReact Native:
bash
npx react-native run-iosor
或
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
常见错误
| Mistake | Fix |
|---|---|
| Forgot to wrap app with Auth0Provider | All components using useAuth0() must be children of Auth0Provider |
| Forgot to configure deep linking | Add URL scheme to iOS Info.plist and Android AndroidManifest.xml (see Step 3) |
| Callback URL mismatch | Ensure callback URL in Auth0 Dashboard matches your app's URL scheme (e.g., |
| iOS build fails after install | Run |
| App created as SPA type in Auth0 | Must be Native application type for mobile apps |
| Not handling auth errors | Wrap authorize/clearSession calls in try-catch blocks |
| Deep link not working on Android | Verify |
| 错误 | 修复方案 |
|---|---|
| 忘记用Auth0Provider包裹应用 | 所有使用useAuth0()的组件必须是Auth0Provider的子组件 |
| 忘记配置深度链接 | 为iOS Info.plist和Android AndroidManifest.xml添加URL scheme(见步骤3) |
| 回调URL不匹配 | 确保Auth0控制台中的回调URL与应用的URL scheme一致(例如: |
| 安装后iOS构建失败 | 运行 |
| Auth0中应用创建为SPA类型 | 移动应用必须设置为Native应用类型 |
| 未处理认证错误 | 将authorize/clearSession调用包裹在try-catch块中 |
| Android上深度链接无法工作 | 验证RedirectActivity已设置 |
Related Skills
相关技能
- - Basic Auth0 setup
auth0-quickstart - - Migrate from another auth provider
auth0-migration - - Add Multi-Factor Authentication
auth0-mfa
- - Auth0基础设置
auth0-quickstart - - 从其他认证提供商迁移
auth0-migration - - 添加多因素认证
auth0-mfa
Quick Reference
快速参考
Core Hook API:
- - Main hook for authentication
useAuth0() - - Initiate login
authorize() - - Logout
clearSession() - - User profile object
user - - Get tokens for API calls
getCredentials() - - Loading state
isLoading
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:
- - 主要认证Hook
useAuth0() - - 发起登录
authorize() - - 登出
clearSession() - - 用户资料对象
user - - 获取用于API调用的令牌
getCredentials() - - 加载状态
isLoading
常见使用场景:
- 登录/登出 → 见上方步骤5
- 安全令牌存储 → 由自动处理
Auth0Provider - 生物识别认证 → 模式指南
- 使用令牌调用API → 模式指南
- 令牌刷新 → 由自动处理
getCredentials()