express-oauth2-jwt-bearer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNode OAuth2 JWT Bearer Integration
Node OAuth2 JWT Bearer 集成
The 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.
express-oauth2-jwt-bearerAgent instruction: Before providing SDK setup instructions, fetch the latest release version by running:bashgh api repos/auth0/node-oauth2-jwt-bearer/releases/latest --jq '.tag_name'Use the returned version in alldependency lines instead of any hardcoded version below.package.json
express-oauth2-jwt-bearerAgent说明: 在提供SDK设置说明之前,运行以下命令获取最新版本:bashgh 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
- npm 或 yarn
- 已配置API(资源服务器)的Auth0账户
- Auth0 CLI(用于自动设置):
npm install -g @auth0/auth0-cli
When NOT to Use
不适用于以下场景
| Use Case | Recommended Skill |
|---|---|
| Building a server-side web app with login UI (Express sessions) | |
| Building a Next.js app with server-side auth | |
| Building a React/Angular/Vue SPA | |
| Building a React Native or mobile app | |
| ASP.NET Core Web API | |
| Go API with JWT middleware | |
| Python API (Flask/FastAPI) | |
Node.js API using the older | |
| 使用场景 | 推荐技能 |
|---|---|
| 构建带登录UI的服务器端Web应用(Express会话) | |
| 构建带服务器端认证的Next.js应用 | |
| 构建React/Angular/Vue单页应用(SPA) | |
| 构建React Native或移动应用 | |
| ASP.NET Core Web API | |
| 带JWT中间件的Go API | |
| Python API(Flask/FastAPI) | |
使用旧版 | |
Quick Start Workflow
快速开始流程
Agent instruction: Follow these steps to integrateinto the user's Node.js API project.express-oauth2-jwt-bearer
Fetch latest version (see instruction above). Install the SDK:bashnpm install express-oauth2-jwt-bearer Configure Auth0 — follow. If the user already provided their Auth0 Domain and API Audience in the prompt, use them directly — skip the bootstrap script and do NOT callreferences/setup.mdto re-confirm. Otherwise, offer automatic setup via bootstrap script or manual setup.AskUserQuestion Set up middleware — add toorapp.js:server.jsjavascriptimport { 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 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 }); }); Add RBAC (optional) — useorrequiredScopes()for permission-based access:claimIncludes()javascriptimport { auth, requiredScopes, claimIncludes } from 'express-oauth2-jwt-bearer'; app.get('/api/messages', checkJwt, requiredScopes('read:messages'), (req, res) => { res.json({ messages: [] }); });Important:accepts a single argument — a space-separated string or an array. Do NOT pass multiple string arguments:requiredScopessilently ignores everything after the first. UserequiredScopes('read:msg', 'write:msg')orrequiredScopes('read:msg write:msg')instead.requiredScopes(['read:msg', 'write:msg']) Verify the integration — build and test:bashnode server.js curl http://localhost:3000/api/private # should return 401 curl -H "Authorization: Bearer <token>" http://localhost:3000/api/private # should return 200 Failcheck: If the server fails to start or tokens are rejected unexpectedly, checkfor common issues. After 5-6 failed iterations, usereferences/api.mdto ask the user for more details about their environment.AskUserQuestion
Agent说明: 按照以下步骤将集成到用户的Node.js API项目中。express-oauth2-jwt-bearer
获取最新版本(见上方说明)。 安装SDK:bashnpm install express-oauth2-jwt-bearer 配置Auth0 — 遵循中的步骤。如果用户已在提示中提供Auth0域名和API受众,则直接使用这些信息 — 跳过引导脚本,不要调用references/setup.md再次确认。否则,提供通过引导脚本自动设置或手动设置两种选项。AskUserQuestion 设置中间件 — 添加到或app.js:server.jsjavascriptimport { auth } from 'express-oauth2-jwt-bearer'; const checkJwt = auth({ issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}`, audience: process.env.AUTH0_AUDIENCE, }); app.use(checkJwt); // 全局应用,或按路由应用 保护端点 — 全局应用中间件或针对特定路由应用:javascript// 全局保护 app.use(checkJwt); // 或按路由保护 app.get('/api/private', checkJwt, (req, res) => { res.json({ sub: req.auth.payload.sub }); }); 添加RBAC(可选) — 使用或requiredScopes()实现基于权限的访问控制:claimIncludes()javascriptimport { 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']) 验证集成效果 — 构建并测试:bashnode server.js curl http://localhost:3000/api/private # 应返回401 curl -H "Authorization: Bearer <token>" http://localhost:3000/api/private # 应返回200 故障排查: 如果服务器无法启动或令牌意外被拒绝,请查看中的常见问题。经过5-6次失败尝试后,使用references/api.md向用户询问更多关于其环境的详细信息。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
常见错误
| Mistake | Symptom | Fix |
|---|---|---|
| Created an Application instead of an API in Auth0 Dashboard | Token validation fails; wrong audience | Create a new API (Resource Server) in Auth0 Dashboard → APIs |
| Audience doesn't match API identifier exactly | | Copy the exact API Identifier string from Auth0 Dashboard → APIs |
Domain includes | | Use hostname only: |
Checking | 403 always returned or permissions ignored | Use |
| CORS not configured before auth middleware | Preflight OPTIONS requests return 401 | Add |
| | Add |
| | Verify |
| 错误 | 症状 | 修复方案 |
|---|---|---|
| 在Auth0控制台中创建了应用而非API | 令牌验证失败;受众错误 | 在Auth0控制台 → APIs中创建新的API(资源服务器) |
| 受众与API标识符不完全匹配 | | 从Auth0控制台 → APIs中复制准确的API标识符字符串 |
域名包含 | 启动时出现 | 仅使用主机名: |
为RBAC检查 | 始终返回403或权限被忽略 | 对基于权限范围的RBAC使用 |
| 在认证中间件之前未配置CORS | 预检OPTIONS请求返回401 | 在中间件链中,将 |
未加载 | 域名/受众为 | 在入口文件顶部添加 |
| | 验证 |
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
核心中间件
| Function | Description | Returns |
|---|---|---|
| JWT Bearer validation middleware | |
| Validates token has all required scopes | |
| Validates token has at least one scope | |
| Validates a claim equals a value | |
| Validates claim includes all values | |
| Custom claim validation function | |
| 函数 | 描述 | 返回值 |
|---|---|---|
| JWT Bearer验证中间件 | |
| 验证令牌包含所有所需权限范围 | |
| 验证令牌至少包含一个指定权限范围 | |
| 验证声明等于指定值 | |
| 验证声明包含所有指定值 | |
| 自定义声明验证函数 | |
Configuration Options
配置选项
| Option | Type | Description |
|---|---|---|
| | Auth0 domain with |
| | API Identifier from Auth0 Dashboard (required unless using env vars) |
| | Signing algorithm (default: |
| | Set |
| | Clock skew tolerance in seconds (no default; undefined unless set) |
| | DPoP configuration (see integration.md) |
| 选项 | 类型 | 描述 |
|---|---|---|
| | 带 |
| | Auth0控制台中的API标识符(除非使用环境变量,否则为必填项) |
| | 签名算法(默认: |
| | 设置为 |
| | 时钟偏差容忍度(秒);无默认值,除非手动设置 |
| | DPoP配置(见integration.md) |
Environment Variables
环境变量
| Variable | Description |
|---|---|
| Auth0 domain with |
| API Identifier (auto-detected by SDK) |
| 变量 | 描述 |
|---|---|
| 带 |
| API标识符(SDK会自动检测) |
Request Object
请求对象
After successful validation, contains:
req.authtypescript
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.authtypescript
req.auth.payload // 解码后的JWT负载(sub, iss, aud, exp, permissions等)
req.auth.header // JWT头部(alg, typ, kid)
req.auth.token // 原始JWT字符串SDK Architecture
SDK架构
The monorepo contains three packages:
node-oauth2-jwt-bearer| Package | Purpose |
|---|---|
| Main package. Express middleware for JWT Bearer validation. Published to npm. |
| Low-level JWT verification utilities (used internally). |
| RFC 6750 Bearer token extraction (used internally). |
In practice, you only install and import .
express-oauth2-jwt-bearernode-oauth2-jwt-bearer| 包 | 用途 |
|---|---|
| 主包。用于JWT Bearer验证的Express中间件。发布至npm。 |
| 底层JWT验证工具(内部使用)。 |
| RFC 6750 Bearer令牌提取工具(内部使用)。 |
实际使用中,您只需安装并导入即可。
express-oauth2-jwt-bearerAuth Flow Comparison
认证流程对比
| Auth Pattern | SDK | When to Use |
|---|---|---|
| JWT Bearer (stateless) | | APIs called by SPAs, mobile apps, M2M clients |
| Session-based (stateful) | | Web apps with login UI and server-side sessions |
| 认证模式 | SDK | 使用场景 |
|---|---|---|
| JWT Bearer(无状态) | | 供SPA、移动应用、M2M客户端调用的API |
| 基于会话(有状态) | | 带登录UI和服务器端会话的Web应用 |
Testing Quick Reference
测试快速参考
bash
undefinedbash
undefinedGet 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"
-H "Origin: http://localhost:5173"
-H "Access-Control-Request-Method: GET"
-H "Access-Control-Request-Headers: Authorization"
undefinedcurl -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"
-H "Origin: http://localhost:5173"
-H "Access-Control-Request-Method: GET"
-H "Access-Control-Request-Headers: Authorization"
undefined