jwt.strategy.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * @Author: 白雾茫茫丶<baiwumm.com>
  3. * @Date: 2024-08-01 16:32:15
  4. * @LastEditors: 白雾茫茫丶<baiwumm.com>
  5. * @LastEditTime: 2024-08-05 14:06:24
  6. * @Description: JWT 鉴权模块
  7. */
  8. import { Injectable, UnauthorizedException } from '@nestjs/common';
  9. import { PassportStrategy } from '@nestjs/passport';
  10. import { Request } from 'express';
  11. import { ExtractJwt, Strategy } from 'passport-jwt';
  12. import { PrismaService } from '@/modules/prisma/prisma.service';
  13. @Injectable()
  14. export class JwtStrategy extends PassportStrategy(Strategy) {
  15. constructor(private prisma: PrismaService) {
  16. super({
  17. // 提供从请求中提取 JWT 的方法。我们将使用在 API 请求的授权头中提供token的标准方法
  18. jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  19. // 为了明确起见,我们选择默认的 false 设置,
  20. // 它将确保 JWT 没有过期的责任委托给 Passport 模块。
  21. // 这意味着,如果我们的路由提供了一个过期的 JWT ,请求将被拒绝,并发送 401 未经授权的响应。Passport 会自动为我们办理
  22. ignoreExpiration: false,
  23. // 使用权宜的选项来提供对称的秘密来签署令牌
  24. secretOrKey: process.env.JWT_SECRET,
  25. passReqToCallback: true,
  26. });
  27. }
  28. async validate(req: Request, payload: CommonType.TokenPayload) {
  29. // 获取当前 token
  30. const token = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
  31. // 缺少令牌
  32. if (!token) {
  33. throw new UnauthorizedException('未登录');
  34. }
  35. const user = await this.prisma.user.findUnique({
  36. where: {
  37. id: payload.sub,
  38. },
  39. });
  40. if (!user) {
  41. throw new UnauthorizedException('token令牌非法,请重新登录');
  42. }
  43. return payload;
  44. }
  45. }