91 lines
2.2 KiB
TypeScript
Executable File
91 lines
2.2 KiB
TypeScript
Executable File
/**
|
||
* JWT认证中间件
|
||
*/
|
||
import { type Request, type Response, type NextFunction } from 'express';
|
||
import jwt from 'jsonwebtoken';
|
||
|
||
// JWT密钥
|
||
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
|
||
|
||
// 扩展Request接口以包含用户信息
|
||
declare global {
|
||
namespace Express {
|
||
interface Request {
|
||
user?: {
|
||
id: number;
|
||
username: string;
|
||
email: string;
|
||
role: string;
|
||
};
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* JWT认证中间件
|
||
*/
|
||
export function authenticateToken(req: Request, res: Response, next: NextFunction): void {
|
||
console.log('认证中间件开始,请求路径:', req.path);
|
||
const authHeader = req.headers['authorization'];
|
||
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
|
||
console.log('认证头:', authHeader ? '存在' : '不存在');
|
||
|
||
if (!token) {
|
||
console.log('错误: 访问令牌缺失');
|
||
res.status(401).json({
|
||
success: false,
|
||
message: '访问令牌缺失'
|
||
});
|
||
return;
|
||
}
|
||
|
||
try {
|
||
console.log('开始验证JWT token');
|
||
const decoded = jwt.verify(token, JWT_SECRET) as any;
|
||
req.user = {
|
||
id: decoded.id,
|
||
username: decoded.username,
|
||
email: decoded.email,
|
||
role: decoded.role
|
||
};
|
||
console.log('JWT验证成功,用户信息:', req.user);
|
||
console.log('认证中间件完成,调用next()');
|
||
next();
|
||
} catch (error) {
|
||
console.log('JWT验证失败:', error);
|
||
res.status(403).json({
|
||
success: false,
|
||
message: '访问令牌无效或已过期'
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 可选认证中间件(不强制要求token)
|
||
*/
|
||
export function optionalAuth(req: Request, res: Response, next: NextFunction): void {
|
||
const authHeader = req.headers['authorization'];
|
||
const token = authHeader && authHeader.split(' ')[1];
|
||
|
||
if (token) {
|
||
try {
|
||
const decoded = jwt.verify(token, JWT_SECRET) as any;
|
||
req.user = {
|
||
id: decoded.id,
|
||
username: decoded.username,
|
||
email: decoded.email,
|
||
role: decoded.role
|
||
};
|
||
} catch (error) {
|
||
// 忽略token验证错误,继续处理请求
|
||
console.warn('可选认证token验证失败:', error);
|
||
}
|
||
}
|
||
|
||
next();
|
||
}
|
||
|
||
export default {
|
||
authenticateToken,
|
||
optionalAuth
|
||
}; |