关于 auth0-express
为使用 Express.js 的服务端应用提供 Auth0 登录集成指南,基于 express-openid-connect。内容涵盖会话认证、受保护路由及外部 API 令牌配置。
主要功能
- 01配置 express-openid-connect 中间件
- 02创建登录、登出和回调端点
- 03使用中间件保护指定路由
- 04配置访问外部 API 的令牌
适用场景
- 01为 Express.js 网站添加 Auth0 登录
- 02限制用户访问特定路由
- 03获取访问令牌并调用下游 API
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ auth0/ agent-skills --skill auth0-express安装后在 Claude Code 中输入/auth0-express确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/api.mdintegration.mdsetup.md详细介绍
Auth0 Express 集成
使用 express-openid-connect 为 Express.js Web 应用添加身份验证。
前提条件
- Express.js 应用
- 已配置的 Auth0 账户和应用
- 如果尚未设置 Auth0,请先使用
auth0-quickstart技能
不适用场景
- 单页应用 - 客户端身份验证请使用
auth0-react、auth0-vue或auth0-angular - Next.js 应用 - 使用
auth0-nextjs技能,该技能同时处理客户端和服务端 - 移动应用 - React Native/Expo 请使用
auth0-react-native - 无状态 API - 请使用 JWT 验证中间件,而非基于会话的身份验证
- 微服务 - 服务间身份验证请使用 JWT 验证
快速入门工作流
1. 安装 SDK
npm install express-openid-connect dotenv
2. 配置环境
使用 Auth0 CLI 自动设置时,请参阅设置指南,获取完整脚本。
手动设置时:
创建 .env:
SECRET=<openssl-rand-hex-32>
BASE_URL=http://localhost:3000
CLIENT_ID=your-client-id
CLIENT_SECRET=your-client-secret
ISSUER_BASE_URL=https://your-tenant.auth0.com
AUDIENCE=https://your-api-identifier # only required if calling external APIs (Step 3a)
生成密钥:openssl rand -hex 32
3. 配置身份验证中间件
更新 Express 应用(app.js 或 index.js):
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.SECRET,
baseURL: process.env.BASE_URL,
clientID: process.env.CLIENT_ID,
issuerBaseURL: process.env.ISSUER_BASE_URL,
clientSecret: process.env.CLIENT_SECRET
}));
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
需要调用外部 API? 如果需要下游 API 的访问令牌,必须添加
authorizationParams— 请参阅下方的步骤 3a。
这会自动创建:
/login- 登录端点/logout- 登出端点/callback- OAuth 回调
3a. 配置用于 API 访问的中间件(调用外部 API 时)
需要外部 API 的访问令牌时,audience 必须放在 authorizationParams 内 — 将其放在顶层会被静默忽略,并且不会签发访问令牌。
// SDK auto-loads SECRET, BASE_URL, CLIENT_ID, ISSUER_BASE_URL, CLIENT_SECRET from env vars
app.use(auth({
authRequired: false,
auth0Logout: true,
authorizationParams: { // ← required for access tokens
response_type: 'code', // ← required: authorization code flow
audience: process.env.AUDIENCE, // ← API identifier (never top-level)
scope: 'openid profile email'
}
}));
然后在路由中访问令牌:
app.get('/api-call', requiresAuth(), async (req, res) => {
const { access_token } = req.oidc.accessToken; // object, not a string
const response = await fetch('https://your-api.com/data', {
headers: { Authorization: `Bearer ${access_token}` }
});
res.json(await response.json());
});
4. 添加路由
// 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>
`}
`);
});
5. 测试身份验证
启动服务器:
node app.js
访问 http://localhost:3000 并测试登录流程。
详细文档
常见错误
| 错误 | 修复方法 |
|---|---|
| 忘记在 Auth0 Dashboard 中添加回调 URL | 将 /callback 路径添加到 Allowed Callback URLs(例如,http://localhost:3000/callback) |
| 未设置 SECRET 或密钥强度不足 | 使用 openssl rand -hex 32 生成安全密钥,并在 .env 中将其存储为 SECRET |
| 全局设置 authRequired: true | 将其设为 false,并在特定路由上使用 requiresAuth() 中间件 |
| 在 Auth0 中将应用创建为 SPA 类型 | 服务端身份验证必须使用 Regular Web Application 类型 |
| 会话密钥暴露在代码中 | 始终使用环境变量,绝不要将密钥硬编码 |
| 生产环境的 baseURL 错误 | 更新 BASE_URL,使其与生产域名一致 |
| 未处理登出时的 returnTo | 将域名添加到 Auth0 Dashboard 中的 Allowed Logout URLs |
将 audience 作为顶层配置键 | 将 audience 移至 authorizationParams 内,并设置 response_type: 'code' 和 scope — 顶层的 audience 会被静默忽略,不会签发访问令牌 |
将 req.oidc.accessToken 当作字符串使用 | 它是一个对象 — 使用 const { access_token } = req.oidc.accessToken 解构 |
相关技能
auth0-quickstart- Auth0 基础设置auth0-migration- 从其他身份验证提供商迁移auth0-mfa- 添加多重身份验证auth0-cli- 从终端管理 Auth0 资源
快速参考
中间件选项:
authRequired- 要求所有路由都进行身份验证(默认:false)auth0Logout- 启用 /logout 端点(默认:false)secret- 会话密钥(必填)baseURL- 应用程序 URL(必填)clientID- Auth0 客户端 ID(必填)issuerBaseURL- Auth0 租户 URL(必填)
请求属性:
req.oidc.isAuthenticated()- 检查用户是否已登录req.oidc.user- 用户资料对象req.oidc.accessToken- 访问令牌对象({ access_token, token_type, expires_in });expires_in表示剩余秒数。可通过const { access_token } = req.oidc.accessToken解构。还提供isExpired()和refresh()方法。仅在配置了包含audience和response_type: 'code'的authorizationParams时才会填充req.oidc.idToken- ID 令牌req.oidc.refreshToken- 刷新令牌
常见用例:
- 受保护的路由 → 使用
requiresAuth()中间件(参见步骤 4) - 检查身份验证状态 →
req.oidc.isAuthenticated() - 获取用户信息 →
req.oidc.user - 调用 API → 集成指南
参考资料
评论
支持 Markdown