PassportJS、NestJS:AuthGuard('jwt') 的 canActivate 方法

Rya*_* Ro 9 passport.js nestjs passport-jwt nestjs-passport nestjs-jwt

有谁知道我在哪里可以看到 AuthGuard('jwt') 中 canActivate 方法的完整代码?我意识到 canActivate 方法通过使用 console.log() 调用 JwtStrategy 验证方法,如下所示:

// jwt.strategy.ts

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private readonly usersService: UsersService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: true,
      secretOrKey: configService.get<string>('JWT_SECRET'),
    });
  }

  async validate(payload: any) {
    try {
      const user = await this.usersService.getUserById(payload.id);
      // console.log is here
      console.log(user);
      return user;
    } catch (e) {
      console.log(e);
      return null;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用原始的 canActivate 方法,则会调用 console.log 。我认为 JwtStrategy 是一个中间件,因此只要有请求就会调用 validate 方法。但是,当我尝试重写 canActivate 方法来添加授权时,不会调用 JwtStrategy validate 方法中的 console.log:

// jwt-auth.guard.ts

import { ExecutionContext, Injectable } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }

  canActivate(context: ExecutionContext): boolean {
    try {
      // Override: handle authorization
      // return true or false
      // Should JwtStrategy.validate(something) be called here?
    } catch (e) {
      console.log(e);
      return false;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我试图找到 AuthGuard('jwt') 的原始代码以理解其逻辑,但我无法做到。任何帮助将不胜感激,谢谢!

Jay*_*iel 13

好的,这将是一次非常有趣的深入探讨。系好安全带。

Middleware因为 NestJS 中仍然存在 Express 方法;也就是说,这不是 Express 中间件意义上的普通中间件。正如您所提到的,AuthGuard()#canActivate()最终会调用适当的PassportStrategy. 这些策略专门在第 40-41 行被调用的地方注册。这注册了要用于 的passport.use()护照策略类的方法。大多数底层逻辑都非常抽象,阅读时可能会丢失上下文,因此请花点时间理解类、mixin(返回类的函数)和继承的概念。validatepassport.verify()

AuthGuard 的第 51 行passportFn最初创建的地方,在这个passportFn Passport.authenticate中被调用(passport.verify在它的引擎盖下调用)(阅读 Passport 的代码更令人困惑,所以我会让你在需要时运行它)。

如果您想在canActivate()方法中添加一些额外的逻辑,您可以最终调用最终调用的super.canActivate(context)原始方法,从而. 那可能看起来像canActivate()passport.authenticate()<Strategy>#validate

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

  async canActivate(context: ExecutionContext): Promise<boolean> {
    // custom logic can go here
    const parentCanActivate = (await super.canActivate(context)) as boolean; // this is necessary due to possibly returning `boolean | Promise<boolean> | Observable<boolean>
    // custom logic goes here too
    return parentCanActivate && customCondition;
  }
}
Run Code Online (Sandbox Code Playgroud)