如何使用 JWT 策略在 NestJS 框架中实现 'Remember me' 特性

How to implement 'Remember me' feature in NestJS framework with JWT strategy

我正在尝试使用 NestJS 框架实现记住我的功能,我已经实现了 Jwt 和本地策略并像这样工作:

import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get('JWT_SECRET'),
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.email };
  }
}

本地攻略:

import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../services/auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({ usernameField: 'email' });
  }

  async validate(email: string, password: string): Promise<any> {
    const user = await this.authService.validateUser(email, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

想到了通过ignoreExpiration flag来解决的方法,请问各位大佬知道用NestJS框架实现的方法吗?尝试搜索文档,但似乎那里没有。

为了将来参考,我找到了解决方案。

在 jwtService 中,我使用 this.jwtService.sign(payload) 方法生成一个令牌,在这个方法中,我可以访问一个名为 expiresIn 的标志(比 ignoreExpiration 标志更安全),所以我传递了一个api 的布尔变量以检查它是否已检查记忆并相应地设置此标志。看起来像这样

remember
  ? (token = this.jwtService.sign(payload, { expiresIn: '60d' }))
  : (token = this.jwtService.sign(payload, { expiresIn: '1d' }));