auth0-express

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Auth0 Express Integration

Auth0 Express 集成

Add authentication to Express.js web applications using express-openid-connect.

使用express-openid-connect为Express.js Web应用添加认证功能。

Prerequisites

前置条件

  • Express.js application
  • Auth0 account and application configured
  • If you don't have Auth0 set up yet, use the
    auth0-quickstart
    skill first
  • Express.js 应用
  • 已配置的Auth0账号和应用
  • 若尚未设置Auth0,请先使用
    auth0-quickstart
    技能

When NOT to Use

不适用于以下场景

  • Single Page Applications - Use
    auth0-react
    ,
    auth0-vue
    , or
    auth0-angular
    for client-side auth
  • Next.js applications - Use
    auth0-nextjs
    skill which handles both client and server
  • Mobile applications - Use
    auth0-react-native
    for React Native/Expo
  • Stateless APIs - Use JWT validation middleware instead of session-based auth
  • Microservices - Use JWT validation for service-to-service auth

  • 单页应用 - 客户端认证请使用
    auth0-react
    auth0-vue
    auth0-angular
  • Next.js 应用 - 请使用
    auth0-nextjs
    技能,它同时支持客户端和服务端
  • 移动应用 - React Native/Expo请使用
    auth0-react-native
  • 无状态API - 请使用JWT验证中间件而非基于会话的认证
  • 微服务 - 服务间认证请使用JWT验证

Quick Start Workflow

快速开始流程

1. Install SDK

1. 安装SDK

bash
npm install express-openid-connect dotenv
bash
npm install express-openid-connect dotenv

2. Configure Environment

2. 配置环境

For automated setup with Auth0 CLI, see Setup Guide for complete scripts.
For manual setup:
Create
.env
:
bash
AUTH0_SECRET=<openssl-rand-hex-32>
AUTH0_BASE_URL=http://localhost:3000
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
AUTH0_ISSUER_BASE_URL=https://your-tenant.auth0.com
Generate secret:
openssl rand -hex 32
使用Auth0 CLI自动配置,请查看设置指南获取完整脚本。
手动配置:
创建
.env
文件:
bash
AUTH0_SECRET=<openssl-rand-hex-32>
AUTH0_BASE_URL=http://localhost:3000
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
AUTH0_ISSUER_BASE_URL=https://your-tenant.auth0.com
生成密钥:
openssl rand -hex 32

3. Configure Auth Middleware

3. 配置认证中间件

Update your Express app (
app.js
or
index.js
):
javascript
require('dotenv').config();
const express = require('express');
const { auth, requiresAuth } = require('express-openid-connect');

const app = express();

// Configure Auth0 middleware
app.use(auth({
  authRequired: false,  // Don't require auth for all routes
  auth0Logout: true,    // Enable logout endpoint
  secret: process.env.AUTH0_SECRET,
  baseURL: process.env.AUTH0_BASE_URL,
  clientID: process.env.AUTH0_CLIENT_ID,
  issuerBaseURL: process.env.AUTH0_ISSUER_BASE_URL,
  clientSecret: process.env.AUTH0_CLIENT_SECRET
}));

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
This automatically creates:
  • /login
    - Login endpoint
  • /logout
    - Logout endpoint
  • /callback
    - OAuth callback
更新你的Express应用(
app.js
index.js
):
javascript
require('dotenv').config();
const express = require('express');
const { auth, requiresAuth } = require('express-openid-connect');

const app = express();

// 配置Auth0中间件
app.use(auth({
  authRequired: false,  // 不为所有路由强制要求认证
  auth0Logout: true,    // 启用登出端点
  secret: process.env.AUTH0_SECRET,
  baseURL: process.env.AUTH0_BASE_URL,
  clientID: process.env.AUTH0_CLIENT_ID,
  issuerBaseURL: process.env.AUTH0_ISSUER_BASE_URL,
  clientSecret: process.env.AUTH0_CLIENT_SECRET
}));

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
这会自动创建:
  • /login
    - 登录端点
  • /logout
    - 登出端点
  • /callback
    - OAuth回调端点

4. Add Routes

4. 添加路由

javascript
// Public route
app.get('/', (req, res) => {
  res.send(req.oidc.isAuthenticated() ? 'Logged in' : 'Logged out');
});

// Protected route
app.get('/profile', requiresAuth(), (req, res) => {
  res.send(`
    <h1>Profile</h1>
    <p>Name: ${req.oidc.user.name}</p>
    <p>Email: ${req.oidc.user.email}</p>
    <pre>${JSON.stringify(req.oidc.user, null, 2)}</pre>
    <a href="/logout">Logout</a>
  `);
});

// Login/logout links
app.get('/', (req, res) => {
  res.send(`
    ${req.oidc.isAuthenticated() ? `
      <p>Welcome, ${req.oidc.user.name}!</p>
      <a href="/profile">Profile</a>
      <a href="/logout">Logout</a>
    ` : `
      <a href="/login">Login</a>
    `}
  `);
});
javascript
// 公开路由
app.get('/', (req, res) => {
  res.send(req.oidc.isAuthenticated() ? '已登录' : '未登录');
});

// 受保护路由
app.get('/profile', requiresAuth(), (req, res) => {
  res.send(`
    <h1>个人资料</h1>
    <p>姓名: ${req.oidc.user.name}</p>
    <p>邮箱: ${req.oidc.user.email}</p>
    <pre>${JSON.stringify(req.oidc.user, null, 2)}</pre>
    <a href="/logout">登出</a>
  `);
});

// 登录/登出链接
app.get('/', (req, res) => {
  res.send(`
    ${req.oidc.isAuthenticated() ? `
      <p>欢迎, ${req.oidc.user.name}!</p>
      <a href="/profile">个人资料</a>
      <a href="/logout">登出</a>
    ` : `
      <a href="/login">登录</a>
    `}
  `);
});

5. Test Authentication

5. 测试认证功能

Start your server:
bash
node app.js
Visit
http://localhost:3000
and test the login flow.

启动服务器:
bash
node app.js
访问
http://localhost:3000
并测试登录流程。

Detailed Documentation

详细文档

  • Setup Guide - Automated setup scripts, environment configuration, Auth0 CLI usage
  • Integration Guide - Protected routes, sessions, API integration, error handling
  • API Reference - Complete middleware API, configuration options, request properties

  • 设置指南 - 自动设置脚本、环境配置、Auth0 CLI使用方法
  • 集成指南 - 受保护路由、会话、API集成、错误处理
  • API参考 - 完整的中间件API、配置选项、请求属性

Common Mistakes

常见错误

MistakeFix
Forgot to add callback URL in Auth0 DashboardAdd
/callback
path to Allowed Callback URLs (e.g.,
http://localhost:3000/callback
)
Missing or weak SECRETGenerate secure secret with
openssl rand -hex 32
and store in .env
Setting authRequired: true globallySet to false and use
requiresAuth()
middleware on specific routes
App created as SPA type in Auth0Must be Regular Web Application type for server-side auth
Session secret exposed in codeAlways use environment variables, never hardcode secrets
Wrong baseURL for productionUpdate AUTH0_BASE_URL to match your production domain
Not handling logout returnToAdd your domain to Allowed Logout URLs in Auth0 Dashboard

错误修复方法
忘记在Auth0控制台添加回调URL
/callback
路径添加到允许的回调URL中(例如:
http://localhost:3000/callback
密钥缺失或强度不足使用
openssl rand -hex 32
生成安全密钥并存储在.env文件中
全局设置authRequired: true设置为false,并在特定路由上使用
requiresAuth()
中间件
在Auth0中创建的应用为SPA类型服务端认证必须使用常规Web应用类型
会话密钥在代码中暴露始终使用环境变量,切勿硬编码密钥
生产环境baseURL错误更新AUTH0_BASE_URL以匹配你的生产域名
未处理登出returnTo在Auth0控制台将你的域名添加到允许的登出URL中

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

快速参考

Middleware Options:
  • authRequired
    - Require auth for all routes (default: false)
  • auth0Logout
    - Enable /logout endpoint (default: false)
  • secret
    - Session secret (required)
  • baseURL
    - Application URL (required)
  • clientID
    - Auth0 client ID (required)
  • issuerBaseURL
    - Auth0 tenant URL (required)
Request Properties:
  • req.oidc.isAuthenticated()
    - Check if user is logged in
  • req.oidc.user
    - User profile object
  • req.oidc.accessToken
    - Access token for API calls
  • req.oidc.idToken
    - ID token
  • req.oidc.refreshToken
    - Refresh token
Common Use Cases:
  • Protected routes → Use
    requiresAuth()
    middleware (see Step 4)
  • Check auth status →
    req.oidc.isAuthenticated()
  • Get user info →
    req.oidc.user
  • Call APIs → Integration Guide

中间件选项:
  • authRequired
    - 为所有路由强制要求认证(默认:false)
  • auth0Logout
    - 启用/logout端点(默认:false)
  • secret
    - 会话密钥(必填)
  • baseURL
    - 应用URL(必填)
  • clientID
    - Auth0客户端ID(必填)
  • issuerBaseURL
    - Auth0租户URL(必填)
请求属性:
  • req.oidc.isAuthenticated()
    - 检查用户是否已登录
  • req.oidc.user
    - 用户资料对象
  • req.oidc.accessToken
    - 用于API调用的访问令牌
  • req.oidc.idToken
    - ID令牌
  • req.oidc.refreshToken
    - 刷新令牌
常见用例:
  • 受保护路由 → 使用
    requiresAuth()
    中间件(见步骤4)
  • 检查认证状态 →
    req.oidc.isAuthenticated()
  • 获取用户信息 →
    req.oidc.user
  • 调用API → 集成指南

References

参考链接