关于 auth0-authentication
面向开发者的 Auth0 认证实施技能,介绍安全认证流程、令牌管理、Actions、多因素认证与测试,也提及用于 IDE 管理操作的 Auth0 MCP 服务。
主要功能
- 01安全的 Auth0 流程指导
- 02公共客户端使用 PKCE
- 03令牌验证与刷新
- 04Auth0 Actions 安全实践
- 05多因素认证与会话指导
- 06认证流程测试
适用场景
- 01实现 SPA 或原生应用登录
- 02保护服务端认证
- 03配置令牌刷新与多因素认证
- 04测试令牌过期和登录流程
MCP 相关
README 提到 Auth0 提供用于 AI 辅助开发的 MCP 服务,可在 IDE 中通过自然语言执行 Auth0 管理操作。
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mindrally/ skills --skill auth0-authentication安装后在 Claude Code 中输入/auth0-authentication确认已加载。
详细介绍
Auth0 身份验证
你是 Auth0 身份验证实现方面的专家。在任何项目中使用 Auth0 时,请遵循以下指南。
核心原则
- 所有 Auth0 通信和回调一律使用 HTTPS
- 将敏感配置(客户端密钥、API 密钥)存储在环境变量中,绝不写入代码
- 为所有身份验证流程实现恰当的错误处理
- 遵循最小权限原则配置作用域和权限
环境变量
# Required Auth0 Configuration
AUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_CLIENT_ID=your-client-id
AUTH0_CLIENT_SECRET=your-client-secret
AUTH0_AUDIENCE=your-api-audience
AUTH0_CALLBACK_URL=https://your-app.com/callback
AUTH0_LOGOUT_URL=https://your-app.com
身份验证流程
使用 PKCE 的授权码流程(推荐用于 SPA 和原生应用)
公共客户端一律使用 PKCE:
import { Auth0Client } from '@auth0/auth0-spa-js';
const auth0 = new Auth0Client({
domain: process.env.AUTH0_DOMAIN,
clientId: process.env.AUTH0_CLIENT_ID,
authorizationParams: {
redirect_uri: window.location.origin,
audience: process.env.AUTH0_AUDIENCE,
},
cacheLocation: 'localstorage', // Use 'memory' for higher security
useRefreshTokens: true,
});
授权码流程(服务端应用)
// Express.js example
const { auth } = require('express-openid-connect');
app.use(
auth({
authRequired: false,
auth0Logout: true,
secret: process.env.AUTH0_SECRET,
baseURL: process.env.BASE_URL,
clientID: process.env.AUTH0_CLIENT_ID,
issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}`,
})
);
Auth0 Actions 最佳实践
Actions 已取代 Rules。请遵循以下指南:
Action 结构
exports.onExecutePostLogin = async (event, api) => {
// 1. Early returns for efficiency
if (!event.user.email_verified) {
api.access.deny('Please verify your email before logging in.');
return;
}
// 2. Use secrets for sensitive data (configured in Auth0 Dashboard)
const apiKey = event.secrets.EXTERNAL_API_KEY;
// 3. Minimize external calls - they affect login latency
// 4. Never log sensitive information
console.log(`User logged in: ${event.user.user_id}`);
// 5. Add custom claims sparingly
api.idToken.setCustomClaim('https://myapp.com/roles', event.authorization?.roles || []);
api.accessToken.setCustomClaim('https://myapp.com/roles', event.authorization?.roles || []);
};
Action 安全规则
- 将密钥存储在 Action Secrets 中,绝不硬编码
- 限制发送到外部服务的数据,绝不发送整个事件对象
- 对外部 API 调用使用较短的超时时间(默认限制为 20 秒)
- 实现恰当的错误处理,避免身份验证失败
令牌管理
访问令牌最佳实践
// Always validate tokens server-side
const { auth, requiredScopes } = require('express-oauth2-jwt-bearer');
const checkJwt = auth({
audience: process.env.AUTH0_AUDIENCE,
issuerBaseURL: `https://${process.env.AUTH0_DOMAIN}/`,
tokenSigningAlg: 'RS256',
});
// Require specific scopes
const checkScopes = requiredScopes('read:messages');
app.get('/api/private-scoped', checkJwt, checkScopes, (req, res) => {
res.json({ message: 'Protected resource' });
});
刷新令牌配置
- 启用刷新令牌轮换
- 设置适当的令牌有效期(访问令牌:最长 1 小时;刷新令牌:根据风险设定)
- 在客户端中实现自动刷新令牌
安全最佳实践
CSRF 防护
// State parameter is automatically handled by Auth0 SDKs
// For custom implementations, always validate the state parameter
const state = generateSecureRandomString();
sessionStorage.setItem('auth0_state', state);
重定向 URI 安全性
- 在 Auth0 Dashboard 中将所有重定向 URI 加入允许列表
- 对重定向 URI 使用精确字符串匹配
- 生产环境中绝不使用通配符重定向 URI
会话管理
// Implement session timeouts
const sessionConfig = {
absoluteDuration: 86400, // 24 hours
inactivityDuration: 3600, // 1 hour of inactivity
};
多因素身份验证
// Enforce MFA for sensitive operations
exports.onExecutePostLogin = async (event, api) => {
// Check if MFA has been completed
if (!event.authentication?.methods?.find(m => m.name === 'mfa')) {
// Trigger MFA challenge
api.authentication.challengeWithAny([
{ type: 'otp' },
{ type: 'push-notification' },
]);
}
};
错误处理
try {
await auth0.loginWithRedirect();
} catch (error) {
if (error.error === 'access_denied') {
// User denied access or email not verified
handleAccessDenied(error);
} else if (error.error === 'login_required') {
// Session expired
handleSessionExpired();
} else {
// Generic error handling
console.error('Authentication error:', error.message);
showUserFriendlyError();
}
}
MCP 集成
Auth0 提供 MCP 服务,用于 AI 辅助开发:
# Initialize Auth0 MCP server for Cursor
npx @auth0/auth0-mcp-server init --client cursor
这使你能够在 IDE 中通过自然语言执行 Auth0 管理操作。
测试
- 使用 Auth0 测试用户进行开发
- 为身份验证流程实现集成测试
- 测试令牌过期和刷新场景
- 在预发布环境中验证 MFA 流程
应避免的常见反模式
- 在未考虑 XSS 风险的情况下将令牌存储在 localStorage 中
- 未在服务端验证令牌
- 使用隐式流程(已弃用)
- 在前端代码中硬编码客户端密钥
- 未实现恰当的注销(同时清除本地会话和 Auth0 会话)
- 在 API 调用中忽略令牌过期
- 在用户元数据中存储过多数据
评论
支持 Markdown