auth0-react

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 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
    auth0-quickstart
    skill first
  • React 16.11+ 应用(基于Vite或Create React App)——支持React 16、17、18和19版本
  • 已配置的Auth0账户和应用
  • 如果您还未设置Auth0,请先使用
    auth0-quickstart
    技能

When NOT to Use

不适用场景

  • Next.js applications - Use
    auth0-nextjs
    skill for both App Router and Pages Router
  • React Native mobile apps - Use
    auth0-react-native
    skill for iOS/Android
  • 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-react
bash
npm install @auth0/auth0-react

2. Configure Environment

2. 配置环境

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

3. Wrap App with Auth0Provider

3. 用Auth0Provider包裹应用

Update
src/main.tsx
(Vite) or
src/index.tsx
(CRA):
tsx
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>
);
更新
src/main.tsx
(Vite)或
src/index.tsx
(CRA):
tsx
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  # Vite

or

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

常见错误

MistakeFix
Forgot to add redirect URI in Auth0 DashboardAdd your application URL (e.g.,
http://localhost:3000
,
https://app.example.com
) to Allowed Callback URLs in Auth0 Dashboard
Using wrong env var prefixVite uses
VITE_
prefix, Create React App uses
REACT_APP_
Not handling loading stateAlways check
isLoading
before rendering auth-dependent UI
Storing tokens in localStorageNever manually store tokens - SDK handles secure storage automatically
Missing Auth0Provider wrapperEntire app must be wrapped in
<Auth0Provider>
Provider not at root levelAuth0Provider must wrap all components that use auth hooks
Wrong import path for env varsVite uses
import.meta.env.VITE_*
, CRA uses
process.env.REACT_APP_*

错误修复方案
忘记在Auth0控制台添加重定向URI将您的应用URL(例如
http://localhost:3000
https://app.example.com
)添加到Auth0控制台的允许回调URL列表中
使用错误的环境变量前缀Vite使用
VITE_
前缀,Create React App使用
REACT_APP_
前缀
未处理加载状态在渲染依赖认证的UI前,务必检查
isLoading
状态
将令牌存储在localStorage中切勿手动存储令牌——SDK会自动处理安全存储
缺少Auth0Provider包裹整个应用必须用
<Auth0Provider>
包裹
Provider未在根层级Auth0Provider必须包裹所有使用认证钩子的组件
环境变量导入路径错误Vite使用
import.meta.env.VITE_*
,CRA使用
process.env.REACT_APP_*

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 Hooks:
  • useAuth0()
    - Main authentication hook
  • isAuthenticated
    - Check if user is logged in
  • user
    - User profile information
  • loginWithRedirect()
    - Initiate login
  • logout()
    - Log out user
  • getAccessTokenSilently()
    - Get access token for API calls
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()
    ——登出用户
  • getAccessTokenSilently()
    ——获取用于API调用的访问令牌
常见使用场景:
  • 登录/登出按钮→参见上方步骤4
  • 受保护路由→集成指南
  • 使用令牌调用API→集成指南
  • 错误处理→集成指南

References

参考链接