import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config'; export interface JwtPayload { userId: string; accountSequence: number; deviceId: string; type: 'access' | 'refresh'; iat: number; exp: number; } @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(private configService: ConfigService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: configService.get('JWT_SECRET', 'default-secret'), }); } async validate(payload: JwtPayload) { if (payload.type !== 'access') { throw new UnauthorizedException('无效的Token类型'); } return { userId: payload.userId, accountSequence: payload.accountSequence, deviceId: payload.deviceId, }; } }