Xen*_*mar 4 nestjs nestjs-passport
所以,我很困惑。我正在慢慢掌握 NestJS,但它的passport工作方式让我感到困惑。
我按照教程操作,一切正常。
\n\n我创建了一个 JWT 策略:
\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n constructor(private prisma: PrismaService) {\n super({\n jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n secretOrKey: \'topSecret51\',\n });\n }\n\n async validate(payload: JwtPayload): Promise<User |\xc2\xa0null> {\n const {\xc2\xa0email } = payload;\n const user = await this.prisma.user.findOne({\n where: { email }\n });\n\n if (!user) {\n throw new UnauthorizedException(\'Athorisation not provided\')\n }\n return user;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n并定义了模块:
\n\n@Module({\n imports: [\n PassportModule.register({\n defaultStrategy: \'jwt\',\n }),\n JwtModule.register({\n secret: \'topSecret51\',\n signOptions: {\n expiresIn: 3600,\n },\n })\n ],\n providers: [UserService, PrismaService, JwtStrategy],\n controllers: [UserController],\n exports: [JwtStrategy, PassportModule],\n})\nexport class UserModule {}\nRun Code Online (Sandbox Code Playgroud)\n\n瞧,一个有效的令牌被发行了。我不明白的是如何passport访问JwtStrategy. Passport 如何知道我的文件夹结构中有一个包含 的文件JwtStrategy?
1.) 它不是由PassportModuleor注入的依赖项JWTModule\n2.) 它不作为参数传递给任何方法
是否有一些幕后魔法可以查看所有提供者并确定它们中是否有任何一个是提供给 的参数的子类PassportStrategy?
NestJS 的护照模块有很多魔力。我会尽我所能来解释这一切是如何运作的,尽管有时它甚至超出了我的能力范围。
首先要注意的是,每个都PassportStrategy 必须扩展抽象 mixin PassportStrategy。Strategy该 mixin从常规护照包中获取 a (passport-jwt在本例中)。该策略有一个默认名称(jwt此处),但您可以传递第二个参数来提供您自己的名称。
CustomStrategyNest 做了一些非常酷的魔法,将的构造函数调用中的值传递super()给护照正常注册。然后,它将其应用于护照的验证回调,这就是该方法必须与护照的预期回调相匹配的CustomStrategy#validate原因。validateverify
现在我们已经用护照完成了一些注册,但是为了正确调用这些,我们需要研究 mixin AuthGuard。通常,我们可以将策略传递给 mixin,并且该策略需要与通行证策略的名称匹配(如本例所示),或者可以在的选项jwt中设置。从这里开始,守卫做了一些魔法,通过名称( 、 、 等)调用策略,并从 Nest 创建的 http 上下文中传递、和。调用结束时,由 的返回值设置。PassportModuledefaultStrategyjwtgooglelocalrequestresponsenextrequest.userpassports.authenticate
| 归档时间: |
|
| 查看次数: |
1643 次 |
| 最近记录: |