express-oauth2-jwt-bearer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Node OAuth2 JWT Bearer Integration

Node OAuth2 JWT Bearer 集成

The
express-oauth2-jwt-bearer
package provides Express middleware for validating Auth0 JWT Bearer access tokens. It handles token extraction, signature verification, audience and issuer validation, and expiry checks per RFC 6750 — letting you focus on business logic rather than JWT parsing.
Agent instruction: Before providing SDK setup instructions, fetch the latest release version by running:
bash
gh api repos/auth0/node-oauth2-jwt-bearer/releases/latest --jq '.tag_name'
Use the returned version in all
package.json
dependency lines instead of any hardcoded version below.
express-oauth2-jwt-bearer
包提供了用于验证Auth0 JWT Bearer访问令牌的Express中间件。它会根据RFC 6750标准处理令牌提取、签名验证、受众与颁发者验证以及过期检查,让您可以专注于业务逻辑而非JWT解析。
Agent说明: 在提供SDK设置说明之前,运行以下命令获取最新版本:
bash
gh api repos/auth0/node-oauth2-jwt-bearer/releases/latest --jq '.tag_name'
将返回的版本号用于所有
package.json
依赖项中,替代下方任何硬编码的版本号。

Prerequisites

前提条件

  • Node.js 18+ (20+ recommended; required for bootstrap script automation)
  • Express 4.x or 5.x
  • npm or yarn
  • An Auth0 account with a configured API (Resource Server)
  • Auth0 CLI (for automatic setup):
    npm install -g @auth0/auth0-cli
  • Node.js 18+(推荐20+;自动化引导脚本需要该版本)
  • Express 4.x或5.x
  • npmyarn
  • 已配置API(资源服务器)的Auth0账户
  • Auth0 CLI(用于自动设置):
    npm install -g @auth0/auth0-cli

When NOT to Use

不适用于以下场景

Use CaseRecommended Skill
Building a server-side web app with login UI (Express sessions)
auth0-express
Building a Next.js app with server-side auth
auth0-nextjs
Building a React/Angular/Vue SPA
auth0-react
,
auth0-angular
,
auth0-vue
Building a React Native or mobile app
auth0-react-native
,
auth0-android
,
auth0-swift
ASP.NET Core Web API
auth0-aspnetcore-api
Go API with JWT middleware
go-jwt-middleware
Python API (Flask/FastAPI)
auth0-api-python
Node.js API using the older
express-jwt
package
express-jwt
使用场景推荐技能
构建带登录UI的服务器端Web应用(Express会话)
auth0-express
构建带服务器端认证的Next.js应用
auth0-nextjs
构建React/Angular/Vue单页应用(SPA)
auth0-react
,
auth0-angular
,
auth0-vue
构建React Native或移动应用
auth0-react-native
,
auth0-android
,
auth0-swift
ASP.NET Core Web API
auth0-aspnetcore-api
带JWT中间件的Go API
go-jwt-middleware
Python API(Flask/FastAPI)
auth0-api-python
使用旧版
express-jwt
包的Node.js API
express-jwt

Quick Start Workflow

快速开始流程

Agent instruction: Follow these steps to integrate
express-oauth2-jwt-bearer
into the user's Node.js API project.
  1. Fetch latest version (see instruction above).
  2. Install the SDK:
    bash
    npm install express-oauth2-jwt-bearer
  3. Configure Auth0 — follow
    references/setup.md
    . If the user already provided their Auth0 Domain and API Audience in the prompt, use them directly — skip the bootstrap script and do NOT call
    AskUserQuestion
    to re-confirm. Otherwise, offer automatic setup via bootstrap script or manual setup.
  4. Set up middleware — add to
    app.js
    or
    server.js
    :
    javascript
    import { auth } from 'express-oauth2-jwt-bearer';
    
    const checkJwt = auth({
      issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}`,
      audience: process.env.AUTH0_AUDIENCE,
    });
    
    app.use(checkJwt); // apply globally, or per-route
  5. Protect endpoints — apply middleware globally or to specific routes:
    javascript
    // Global protection
    app.use(checkJwt);
    
    // Or per-route
    app.get('/api/private', checkJwt, (req, res) => {
      res.json({ sub: req.auth.payload.sub });
    });
  6. Add RBAC (optional) — use
    requiredScopes()
    or
    claimIncludes()
    for permission-based access:
    javascript
    import { auth, requiredScopes, claimIncludes } from 'express-oauth2-jwt-bearer';
    
    app.get('/api/messages', checkJwt, requiredScopes('read:messages'), (req, res) => {
      res.json({ messages: [] });
    });
    Important:
    requiredScopes
    accepts a single argument — a space-separated string or an array. Do NOT pass multiple string arguments:
    requiredScopes('read:msg', 'write:msg')
    silently ignores everything after the first. Use
    requiredScopes('read:msg write:msg')
    or
    requiredScopes(['read:msg', 'write:msg'])
    instead.
  7. Verify the integration — build and test:
    bash
    node server.js
    curl http://localhost:3000/api/private         # should return 401
    curl -H "Authorization: Bearer <token>" http://localhost:3000/api/private  # should return 200
  8. Failcheck: If the server fails to start or tokens are rejected unexpectedly, check
    references/api.md
    for common issues. After 5-6 failed iterations, use
    AskUserQuestion
    to ask the user for more details about their environment.
Agent说明: 按照以下步骤将
express-oauth2-jwt-bearer
集成到用户的Node.js API项目中。
  1. 获取最新版本(见上方说明)。
  2. 安装SDK:
    bash
    npm install express-oauth2-jwt-bearer
  3. 配置Auth0 — 遵循
    references/setup.md
    中的步骤。如果用户已在提示中提供Auth0域名和API受众,则直接使用这些信息 — 跳过引导脚本,不要调用
    AskUserQuestion
    再次确认。否则,提供通过引导脚本自动设置或手动设置两种选项。
  4. 设置中间件 — 添加到
    app.js
    server.js
    javascript
    import { auth } from 'express-oauth2-jwt-bearer';
    
    const checkJwt = auth({
      issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}`,
      audience: process.env.AUTH0_AUDIENCE,
    });
    
    app.use(checkJwt); // 全局应用,或按路由应用
  5. 保护端点 — 全局应用中间件或针对特定路由应用:
    javascript
    // 全局保护
    app.use(checkJwt);
    
    // 或按路由保护
    app.get('/api/private', checkJwt, (req, res) => {
      res.json({ sub: req.auth.payload.sub });
    });
  6. 添加RBAC(可选) — 使用
    requiredScopes()
    claimIncludes()
    实现基于权限的访问控制:
    javascript
    import { auth, requiredScopes, claimIncludes } from 'express-oauth2-jwt-bearer';
    
    app.get('/api/messages', checkJwt, requiredScopes('read:messages'), (req, res) => {
      res.json({ messages: [] });
    });
    重要提示:
    requiredScopes
    接受单个参数 — 空格分隔的字符串或数组。不要传递多个字符串参数:
    requiredScopes('read:msg', 'write:msg')
    会静默忽略第一个参数之后的所有内容。请使用
    requiredScopes('read:msg write:msg')
    requiredScopes(['read:msg', 'write:msg'])
    替代。
  7. 验证集成效果 — 构建并测试:
    bash
    node server.js
    curl http://localhost:3000/api/private         # 应返回401
    curl -H "Authorization: Bearer <token>" http://localhost:3000/api/private  # 应返回200
  8. 故障排查: 如果服务器无法启动或令牌意外被拒绝,请查看
    references/api.md
    中的常见问题。经过5-6次失败尝试后,使用
    AskUserQuestion
    向用户询问更多关于其环境的详细信息。

Detailed Documentation

详细文档

  • Setup Guide — Auth0 API registration, .env configuration, bootstrap script for automated setup, and secret management
  • Integration Patterns — Protected endpoints, RBAC with scopes and claims, DPoP, CORS setup, error handling, and testing with curl
  • API Reference & Testing — Full configuration options, claims reference, complete code example, testing checklist, and common issues
  • 设置指南 — Auth0 API注册、.env配置、自动设置的引导脚本以及密钥管理
  • 集成模式 — 受保护端点、基于权限范围和声明的RBAC、DPoP、CORS设置、错误处理以及使用curl测试
  • API参考与测试 — 完整配置选项、声明参考、完整代码示例、测试清单以及常见问题

Common Mistakes

常见错误

MistakeSymptomFix
Created an Application instead of an API in Auth0 DashboardToken validation fails; wrong audienceCreate a new API (Resource Server) in Auth0 Dashboard → APIs
Audience doesn't match API identifier exactly
401 Unauthorized
— "Audience mismatch"
Copy the exact API Identifier string from Auth0 Dashboard → APIs
Domain includes
https://
prefix
Error: Invalid URL
at startup
Use hostname only:
your-tenant.us.auth0.com
, not
https://...
Checking
scope
claim instead of
permissions
for RBAC
403 always returned or permissions ignoredUse
requiredScopes()
for scope-based RBAC; use
claimIncludes('permissions', 'read:data')
for Auth0 RBAC permission claims
CORS not configured before auth middlewarePreflight OPTIONS requests return 401Add
cors()
middleware before
auth()
in the middleware chain
.env
file not loaded
undefined
for domain/audience
Add
import 'dotenv/config'
at the top of the entry file
req.auth
is undefined
TypeError: Cannot read properties of undefined
Verify
checkJwt
middleware runs before the handler
错误症状修复方案
在Auth0控制台中创建了应用而非API令牌验证失败;受众错误在Auth0控制台 → APIs中创建新的API(资源服务器)
受众与API标识符不完全匹配
401 Unauthorized
— "Audience mismatch"
从Auth0控制台 → APIs中复制准确的API标识符字符串
域名包含
https://
前缀
启动时出现
Error: Invalid URL
仅使用主机名:
your-tenant.us.auth0.com
,而非
https://...
为RBAC检查
scope
声明而非
permissions
始终返回403或权限被忽略对基于权限范围的RBAC使用
requiredScopes()
;对Auth0 RBAC权限声明使用
claimIncludes('permissions', 'read:data')
在认证中间件之前未配置CORS预检OPTIONS请求返回401在中间件链中,将
cors()
中间件添加到
auth()
之前
未加载
.env
文件
域名/受众为
undefined
在入口文件顶部添加
import 'dotenv/config'
req.auth
未定义
TypeError: Cannot read properties of undefined
验证
checkJwt
中间件在处理程序之前运行

Related Skills

相关技能

  • auth0-express — For Express web apps with login UI (sessions, cookies)
  • auth0-nextjs — For Next.js server-side web apps
  • auth0-aspnetcore-api — BACKEND_API reference implementation for .NET
  • go-jwt-middleware — JWT middleware for Go APIs
  • auth0-api-python — JWT validation for Python APIs (Flask/FastAPI)
  • auth0-cli — Manage Auth0 resources from the terminal
  • auth0-express — 适用于带登录UI的Express Web应用(会话、Cookie)
  • auth0-nextjs — 适用于Next.js服务器端Web应用
  • auth0-aspnetcore-api — .NET的BACKEND_API参考实现
  • go-jwt-middleware — Go API的JWT中间件
  • auth0-api-python — Python API(Flask/FastAPI)的JWT验证
  • auth0-cli — 从终端管理Auth0资源

Quick Reference

快速参考

Core Middleware

核心中间件

FunctionDescriptionReturns
auth(options?)
JWT Bearer validation middleware
Handler
— 401 if token invalid/missing
requiredScopes(scopes)
Validates token has all required scopes
Handler
— 403 if scopes missing
scopeIncludesAny(scopes)
Validates token has at least one scope
Handler
— 403 if no match
claimEquals(claim, value)
Validates a claim equals a value
Handler
— 401 if mismatch
claimIncludes(claim, ...values)
Validates claim includes all values
Handler
— 401 if incomplete
claimCheck(fn, desc?)
Custom claim validation function
Handler
— 401 if fn returns false
函数描述返回值
auth(options?)
JWT Bearer验证中间件
Handler
— 令牌无效/缺失时返回401
requiredScopes(scopes)
验证令牌包含所有所需权限范围
Handler
— 权限范围缺失时返回403
scopeIncludesAny(scopes)
验证令牌至少包含一个指定权限范围
Handler
— 无匹配时返回403
claimEquals(claim, value)
验证声明等于指定值
Handler
— 不匹配时返回401
claimIncludes(claim, ...values)
验证声明包含所有指定值
Handler
— 不完整时返回401
claimCheck(fn, desc?)
自定义声明验证函数
Handler
— fn返回false时返回401

Configuration Options

配置选项

OptionTypeDescription
issuerBaseURL
string
Auth0 domain with
https://
(required unless using env vars)
audience
string
API Identifier from Auth0 Dashboard (required unless using env vars)
tokenSigningAlg
string
Signing algorithm (default:
RS256
; use
HS256
for symmetric)
authRequired
boolean
Set
false
to make authentication optional (default:
true
)
clockTolerance
number
Clock skew tolerance in seconds (no default; undefined unless set)
dpop
DPoPOptions
DPoP configuration (see integration.md)
选项类型描述
issuerBaseURL
string
https://
的Auth0域名(除非使用环境变量,否则为必填项)
audience
string
Auth0控制台中的API标识符(除非使用环境变量,否则为必填项)
tokenSigningAlg
string
签名算法(默认:
RS256
;对称加密使用
HS256
authRequired
boolean
设置为
false
可使认证变为可选(默认:
true
clockTolerance
number
时钟偏差容忍度(秒);无默认值,除非手动设置
dpop
DPoPOptions
DPoP配置(见integration.md)

Environment Variables

环境变量

VariableDescription
ISSUER_BASE_URL
Auth0 domain with
https://
(auto-detected by SDK)
AUDIENCE
API Identifier (auto-detected by SDK)
变量描述
ISSUER_BASE_URL
https://
的Auth0域名(SDK会自动检测)
AUDIENCE
API标识符(SDK会自动检测)

Request Object

请求对象

After successful validation,
req.auth
contains:
typescript
req.auth.payload    // Decoded JWT payload (sub, iss, aud, exp, permissions, etc.)
req.auth.header     // JWT header (alg, typ, kid)
req.auth.token      // Raw JWT string
验证成功后,
req.auth
包含以下内容:
typescript
req.auth.payload    // 解码后的JWT负载(sub, iss, aud, exp, permissions等)
req.auth.header     // JWT头部(alg, typ, kid)
req.auth.token      // 原始JWT字符串

SDK Architecture

SDK架构

The
node-oauth2-jwt-bearer
monorepo contains three packages:
PackagePurpose
express-oauth2-jwt-bearer
Main package. Express middleware for JWT Bearer validation. Published to npm.
access-token-jwt
Low-level JWT verification utilities (used internally).
oauth2-bearer
RFC 6750 Bearer token extraction (used internally).
In practice, you only install and import
express-oauth2-jwt-bearer
.
node-oauth2-jwt-bearer
单仓库包含三个包:
用途
express-oauth2-jwt-bearer
主包。用于JWT Bearer验证的Express中间件。发布至npm。
access-token-jwt
底层JWT验证工具(内部使用)。
oauth2-bearer
RFC 6750 Bearer令牌提取工具(内部使用)。
实际使用中,您只需安装并导入
express-oauth2-jwt-bearer
即可。

Auth Flow Comparison

认证流程对比

Auth PatternSDKWhen to Use
JWT Bearer (stateless)
express-oauth2-jwt-bearer
APIs called by SPAs, mobile apps, M2M clients
Session-based (stateful)
@auth0/express-openid-connect
Web apps with login UI and server-side sessions
认证模式SDK使用场景
JWT Bearer(无状态)
express-oauth2-jwt-bearer
供SPA、移动应用、M2M客户端调用的API
基于会话(有状态)
@auth0/express-openid-connect
带登录UI和服务器端会话的Web应用

Testing Quick Reference

测试快速参考

bash
undefined
bash
undefined

Get test token from Auth0 Dashboard → APIs → your API → Test tab

从Auth0控制台 → APIs → 您的API → 测试标签获取测试令牌

Copy the token, then:

复制令牌后执行以下命令:

1. Verify 401 on protected route (no token)

1. 验证受保护路由在无令牌时返回401

2. Verify 200 with valid token

2. 验证使用有效令牌时返回200

curl -H "Authorization: Bearer <paste-token-here>" http://localhost:3000/api/private
curl -H "Authorization: Bearer <paste-token-here>" http://localhost:3000/api/private

3. Verify 403 with valid token but missing scope

3. 验证使用有效令牌但缺少权限范围时返回403

curl -H "Authorization: Bearer <paste-token-here>" http://localhost:3000/api/admin
curl -H "Authorization: Bearer <paste-token-here>" http://localhost:3000/api/admin

4. Verify CORS preflight

4. 验证CORS预检

curl -v -X OPTIONS http://localhost:3000/api/private
-H "Origin: http://localhost:5173"
-H "Access-Control-Request-Method: GET"
-H "Access-Control-Request-Headers: Authorization"
undefined
curl -v -X OPTIONS http://localhost:3000/api/private
-H "Origin: http://localhost:5173"
-H "Access-Control-Request-Method: GET"
-H "Access-Control-Request-Headers: Authorization"
undefined

References

参考链接