starwait/server/middleware/02.auth.ts
2025-04-25 11:33:24 +08:00

32 lines
880 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import consola from "consola";
export default defineEventHandler(event => {
// 跳过无需验证的路由
if (event.path?.startsWith('/api/auth')) return
const {defaultToken} = useRuntimeConfig()
const token = getHeader(event, 'Authorization')?.split('Bearer ')[1];
const t = generateAccessToken({
...defaultToken,
isTrue: false
})
consola.info(`Token ${t}`);
if (!t) {
throw createError({
statusCode: 401,
statusMessage: '未提供认证Token'
})
}
try {
// 验证JWT示例使用jsonwebtoken
const verified = verifyToken(t) // 你的验证逻辑
event.context.auth = verified // 将用户信息挂载到上下文
} catch (e) {
throw createError({
statusCode: 401,
statusMessage: '无效Token'
})
}
})