import { HTTPError } from 'h3'; | |
/** | |
* 认证中间件 - 验证 API 密钥 | |
*/ | |
export const authMiddleware = (event) => { | |
// 跳过健康检查的认证 | |
if (event.path === '/health') { | |
return; | |
} | |
// 只对 API 路由进行认证 | |
if (!event.path?.startsWith('/v1/')) { | |
return; | |
} | |
// 尝试多种方式获取 authorization 头 | |
const authorization = event.headers?.authorization || | |
event.req?.headers?.authorization || | |
event.node?.req?.headers?.authorization; | |
if (!authorization) { | |
throw new HTTPError(401, 'Authorization header is required'); | |
} | |
// 支持 Bearer token 格式 | |
const token = authorization.startsWith('Bearer ') | |
? authorization.slice(7) | |
: authorization; | |
if (!token) { | |
throw new HTTPError(401, 'Invalid authorization format'); | |
} | |
// 验证 token(这里可以根据需要实现更复杂的验证逻辑) | |
if (!isValidApiKey(token)) { | |
throw new HTTPError(401, 'Invalid API key'); | |
} | |
// 将 API 密钥添加到事件上下文中 | |
event.context.apiKey = token; | |
}; | |
/** | |
* 验证 API 密钥 | |
*/ | |
function isValidApiKey(apiKey) { | |
// 简单验证:检查是否为非空字符串 | |
// 在实际应用中,你可能需要: | |
// 1. 检查数据库中的有效密钥 | |
// 2. 验证密钥格式 | |
// 3. 检查密钥权限 | |
return typeof apiKey === 'string' && apiKey.length > 0; | |
} | |