【问题标题】:NestJS authentication strategy - how is it accessed?NestJS 身份验证策略 - 它是如何访问的?
【发布时间】:2020-10-05 07:24:01
【问题描述】:

所以,我很困惑。我慢慢掌握了 NestJS,但 passport 的工作方式让我感到困惑。

我关注了tutorial,一切正常。

我创建了一个 JWT 策略:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(private prisma: PrismaService) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: 'topSecret51',
        });
    }

    async validate(payload: JwtPayload): Promise<User | null> {
        const { email } = payload;
        const user = await this.prisma.user.findOne({
            where: { email }
        });

        if (!user) {
            throw new UnauthorizedException('Athorisation not provided')
        }
        return user;
    }
}

并定义了模块:

@Module({
  imports: [
    PassportModule.register({
      defaultStrategy: 'jwt',
    }),
    JwtModule.register({
      secret: 'topSecret51',
      signOptions: {
        expiresIn: 3600,
      },
    })
  ],
  providers: [UserService, PrismaService, JwtStrategy],
  controllers: [UserController],
  exports: [JwtStrategy, PassportModule],
})
export class UserModule {}

并且一个有效的令牌被发行。我不明白的是passport 是如何访问JwtStrategy 的。护照如何知道我的文件夹结构中有一个文件包含JwtStrategy

1.) 这不是PassportModuleJWTModule 注入的依赖项 2.) 它不作为参数传递给任何方法

是否有一些幕后魔术可以查看所有提供者并确定它们中的任何一个是否是提供给PassportStrategy 的参数的子类?

【问题讨论】:

    标签: nestjs nestjs-passport


    【解决方案1】:

    NestJS 的护照模块有很多神奇之处。我会尽我所能解释这一切是如何运作的,尽管有时它甚至超出了我的范围。

    首先要注意的是每个PassportStrategy必须扩展抽象mixin PassportStrategy。这个 mixin 从普通的护照包(在这种情况下为passport-jwt)中接收一个Strategy。此策略有一个默认名称(此处为jwt),但您可以传递第二个参数来提供您自己的名称。

    Nest 做了一些非常酷的魔法来将来自CustomStrategy 的构造函数的super() 调用的值传递给护照正常注册。然后它将CustomStrategy#validate 应用于passport 的验证回调,这就是validate 方法必须 匹配passport 的预期verify 回调的原因。

    现在我们已经用护照完成了一些注册,但是要正确调用这些,我们需要查看AuthGuard mixin。通常,我们可以将一个策略传递给 mixin,该策略需要匹配一个护照策略的名称(如本例中的jwt),或者可以在PassportModuledefaultStrategy 选项中设置。从这里开始,守卫做了一点魔法,通过名称(jwtgooglelocal 等)调用策略,并从http 上下文 Nest 创建。在调用结束时,request.user 由来自passports.authenticate 的返回值设置。

    【讨论】:

      猜你喜欢
      • 2022-07-19
      • 2021-12-15
      • 2020-10-21
      • 2017-05-20
      • 2020-07-03
      • 2021-08-15
      • 2021-08-22
      • 2019-06-12
      • 2020-04-20
      相关资源
      最近更新 更多