auth0-react
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuth0 React Integration
Auth0 React 集成
Add authentication to React single-page applications using @auth0/auth0-react.
使用@auth0/auth0-react为React单页应用添加认证功能。
Prerequisites
前置条件
- React 16.11+ application (Vite or Create React App) - supports React 16, 17, 18, and 19
- Auth0 account and application configured
- If you don't have Auth0 set up yet, use the skill first
auth0-quickstart
- React 16.11+ 应用(基于Vite或Create React App)——支持React 16、17、18和19版本
- 已配置的Auth0账户和应用
- 如果您还未设置Auth0,请先使用技能
auth0-quickstart
When NOT to Use
不适用场景
- Next.js applications - Use skill for both App Router and Pages Router
auth0-nextjs - React Native mobile apps - Use skill for iOS/Android
auth0-react-native - Server-side rendered React - Use framework-specific SDK (Next.js, Remix, etc.)
- Embedded login - This SDK uses Auth0 Universal Login (redirect-based)
- Backend API authentication - Use express-openid-connect or JWT validation instead
- Next.js应用——针对App Router和Pages Router,请使用技能
auth0-nextjs - React Native移动应用——针对iOS/Android,请使用技能
auth0-react-native - 服务端渲染的React应用——使用框架专属SDK(如Next.js、Remix等)
- 嵌入式登录——本SDK使用Auth0通用登录(基于重定向)
- 后端API认证——请使用express-openid-connect或JWT验证替代
Quick Start Workflow
快速开始流程
1. Install SDK
1. 安装SDK
bash
npm install @auth0/auth0-reactbash
npm install @auth0/auth0-react2. Configure Environment
2. 配置环境
For automated setup with Auth0 CLI, see Setup Guide for complete scripts.
For manual setup:
Create file:
.envVite:
bash
VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-idCreate React App:
bash
REACT_APP_AUTH0_DOMAIN=your-tenant.auth0.com
REACT_APP_AUTH0_CLIENT_ID=your-client-id使用Auth0 CLI自动设置,请查看设置指南获取完整脚本。
手动设置:
创建文件:
.envVite:
bash
VITE_AUTH0_DOMAIN=your-tenant.auth0.com
VITE_AUTH0_CLIENT_ID=your-client-idCreate React App:
bash
REACT_APP_AUTH0_DOMAIN=your-tenant.auth0.com
REACT_APP_AUTH0_CLIENT_ID=your-client-id3. Wrap App with Auth0Provider
3. 用Auth0Provider包裹应用
Update (Vite) or (CRA):
src/main.tsxsrc/index.tsxtsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Auth0Provider
domain={import.meta.env.VITE_AUTH0_DOMAIN} // or process.env.REACT_APP_AUTH0_DOMAIN
clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
authorizationParams={{
redirect_uri: window.location.origin
}}
>
<App />
</Auth0Provider>
</React.StrictMode>
);更新(Vite)或(CRA):
src/main.tsxsrc/index.tsxtsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Auth0Provider
domain={import.meta.env.VITE_AUTH0_DOMAIN} // 或 process.env.REACT_APP_AUTH0_DOMAIN
clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
authorizationParams={{
redirect_uri: window.location.origin
}}
>
<App />
</Auth0Provider>
</React.StrictMode>
);4. Add Authentication UI
4. 添加认证UI
tsx
import { useAuth0 } from '@auth0/auth0-react';
export function LoginButton() {
const { loginWithRedirect, logout, isAuthenticated, user, isLoading } = useAuth0();
if (isLoading) return <div>Loading...</div>;
if (isAuthenticated) {
return (
<div>
<span>Welcome, {user?.name}</span>
<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>
Logout
</button>
</div>
);
}
return <button onClick={() => loginWithRedirect()}>Login</button>;
}tsx
import { useAuth0 } from '@auth0/auth0-react';
export function LoginButton() {
const { loginWithRedirect, logout, isAuthenticated, user, isLoading } = useAuth0();
if (isLoading) return <div>加载中...</div>;
if (isAuthenticated) {
return (
<div>
<span>欢迎,{user?.name}</span>
<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>
登出
</button>
</div>
);
}
return <button onClick={() => loginWithRedirect()}>登录</button>;
}5. Test Authentication
5. 测试认证功能
Start your dev server and test the login flow:
bash
npm run dev # Vite启动开发服务器并测试登录流程:
bash
npm run dev # Viteor
或
npm start # CRA
---npm start # CRA
---Detailed Documentation
详细文档
- Setup Guide - Automated setup scripts (Bash/PowerShell), CLI commands, manual configuration
- Integration Guide - Protected routes, API calls, error handling, advanced patterns
- API Reference - Complete SDK API, configuration options, hooks reference, testing strategies
- 设置指南——自动设置脚本(Bash/PowerShell)、CLI命令、手动配置说明
- 集成指南——受保护路由、API调用、错误处理、高级模式
- API参考——完整SDK API、配置选项、钩子参考、测试策略
Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
| Forgot to add redirect URI in Auth0 Dashboard | Add your application URL (e.g., |
| Using wrong env var prefix | Vite uses |
| Not handling loading state | Always check |
| Storing tokens in localStorage | Never manually store tokens - SDK handles secure storage automatically |
| Missing Auth0Provider wrapper | Entire app must be wrapped in |
| Provider not at root level | Auth0Provider must wrap all components that use auth hooks |
| Wrong import path for env vars | Vite uses |
| 错误 | 修复方案 |
|---|---|
| 忘记在Auth0控制台添加重定向URI | 将您的应用URL(例如 |
| 使用错误的环境变量前缀 | Vite使用 |
| 未处理加载状态 | 在渲染依赖认证的UI前,务必检查 |
| 将令牌存储在localStorage中 | 切勿手动存储令牌——SDK会自动处理安全存储 |
| 缺少Auth0Provider包裹 | 整个应用必须用 |
| Provider未在根层级 | Auth0Provider必须包裹所有使用认证钩子的组件 |
| 环境变量导入路径错误 | Vite使用 |
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 Hooks:
- - Main authentication hook
useAuth0() - - Check if user is logged in
isAuthenticated - - User profile information
user - - Initiate login
loginWithRedirect() - - Log out user
logout() - - Get access token for API calls
getAccessTokenSilently()
Common Use Cases:
- Login/Logout buttons → See Step 4 above
- Protected routes → Integration Guide
- API calls with tokens → Integration Guide
- Error handling → Integration Guide
核心钩子:
- ——主要认证钩子
useAuth0() - ——检查用户是否已登录
isAuthenticated - ——用户资料信息
user - ——发起登录
loginWithRedirect() - ——登出用户
logout() - ——获取用于API调用的访问令牌
getAccessTokenSilently()
常见使用场景:
- 登录/登出按钮→参见上方步骤4
- 受保护路由→集成指南
- 使用令牌调用API→集成指南
- 错误处理→集成指南