使用 JWT 策略的 NestJs 身份验证 - 添加“ignoreNotBefore”验证选项

use*_*448 2 node.js nestjs nestjs-jwt

我在 NestJs 中使用 AuthGuard 来验证请求 jwt 令牌。因为我的服务只是验证令牌而不是创建它,所以它不能使用“nbf”验证,以避免创建令牌的服务器的时间晚于我的服务器的情况。

当使用 jsonwebtoken 库使用纯 Node.js 时,可以轻松添加选项来关闭此验证,方法是添加:

jwt.verify(token, cert, {ignoreNotBefore: true})
Run Code Online (Sandbox Code Playgroud)

这也有效。但是,我该如何使用 Nest 来做到这一点呢?

这是我的守卫:

    @Injectable()
    export class JwtAuthGuard extends AuthGuard('jwt') {

     constructor(private reflector: Reflector,
              private authService: AuthService) {
       super();
     }

     async canActivate(context: ExecutionContext) {
       const isValid = await super.canActivate(context);
       return isValid;
     }

     handleRequest(err, user, info) {
       if (err || !user) {
         Logger.error(`Unauthorized: ${info && info.message}`);
         throw err || new UnauthorizedException();
      }
      return user;
    }
   }
Run Code Online (Sandbox Code Playgroud)

在JWT策略中,我尝试在调用PassportStrategy的“super”时添加ignoreNotBefore选项,但这不起作用:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService,
              private config: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      ignoreNotBefore: true,
      secretOrKey: fs.readFileSync(config.get('auth.secret')),
    });
  }

  validate(payload: any) {
     const isAuthorized = this.authConfig.roles.some((role) => payload.role?.includes(role));
     if(!isAuthorized) {
        Logger.error(`Unauthorized: Invalid role`);
        throw new UnauthorizedException();
    }
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

谢谢。

Iso*_*ted 5

JwtAuthGuard


@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService,
              private config: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      jsonWebTokenOptions: {
        // this object maps to jsonwebtoken verifier options
        ignoreNotBefore: true,
        // ...
        // maybe ignoreExpiration too?
      },
      secretOrKey: fs.readFileSync(config.get('auth.secret')),
    });
  }

  validate(payload: any) {
     const isAuthorized = this.authConfig.roles.some((role) => payload.role?.includes(role));
     if(!isAuthorized) {
        Logger.error(`Unauthorized: Invalid role`);
        throw new UnauthorizedException();
    }
    return true;
  }
}
Run Code Online (Sandbox Code Playgroud)

解释

将您的移动ignoreNotBefore到,jsonWebTokenOptions因为该对象映射到jsonwebtoken验证程序选项。这就像 Nest.js 已经wrappedpassport-jwtpassport-jwtwrapps一样jsonwebtoken。所以根对象中的选项主要是配置策略(护照)而不是配置jsonwebtoken(那么多)。

了解更多

  1. http://www.passportjs.org/packages/passport-jwt/