给所有请求都加上jwt,隐藏生成jwt的secret(放到.env中),隐藏app-secret(放在pm2运行配置文件中,后续直接读取环境配置即可)

This commit is contained in:
2025-10-17 15:28:22 +08:00
parent 9ec6d30573
commit 59706b70d0
70 changed files with 2279 additions and 688 deletions
+17 -5
View File
@@ -11,8 +11,14 @@
import jwt from 'jsonwebtoken';
const { sign, verify, decode } = jwt;
// JWT密钥 - 在生产环境中应该从环境变量读取
const JWT_SECRET = 'gdyc-super-secrets-jjwtt-key-change-this-in-production-20250721-from-login-callback';
// JWT密钥 - 从环境变量读取,如果未设置则抛出错误
const JWT_SECRET: string = (() => {
const secret = process.env.JWT_SECRET;
if (!secret) {
throw new Error('JWT_SECRET environment variable is not set. Please add it to your .env file.');
}
return secret;
})();
// JWT配置
const JWT_CONFIG = {
@@ -104,13 +110,19 @@ export class JWTUtils {
*/
static verifyJWT(token: string): { valid: boolean; payload?: JWTPayload; error?: string } {
try {
const payload = verify(token, JWT_SECRET, {
const decoded = verify(token, JWT_SECRET, {
algorithms: [JWT_CONFIG.algorithm],
issuer: JWT_CONFIG.issuer,
audience: JWT_CONFIG.audience
}) as JWTPayload;
});
return { valid: true, payload };
// 验证返回的payload是否包含必需字段
if (typeof decoded === 'object' && decoded !== null && 'sub' in decoded) {
const payload = decoded as JWTPayload;
return { valid: true, payload };
}
return { valid: false, error: 'JWT载荷格式不正确' };
} catch (error) {
if (error instanceof Error) {
return { valid: false, error: error.message };