import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { Request } from 'express'; export interface JwtPayload { sub: string; // user id openid: string; } @Injectable() export class JwtAuthGuard implements CanActivate { constructor(private readonly jwtService: JwtService) {} async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); const token = this.extractToken(request); if (!token) { throw new UnauthorizedException('未提供访问令牌'); } try { const payload = await this.jwtService.verifyAsync(token); // 将用户信息挂载到 request 上 (request as any).user = payload; } catch { throw new UnauthorizedException('访问令牌无效或已过期'); } return true; } private extractToken(request: Request): string | null { const authorization = request.headers.authorization; if (!authorization) return null; const [type, token] = authorization.split(' '); return type === 'Bearer' ? token : null; } }