所以,我很困惑。我慢慢了解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。)它不是PassportModule
或JWTModule
注入的依赖项
2.)不能将其作为参数传递给任何方法
是否有一些幕后魔术可以检查所有提供程序,并确定其中任何一个是否是提供给PassportStrategy
的参数的子类?
答案 0 :(得分:3)
NestJS的通行证模块具有许多不可思议的功能。我将尽我所能解释一切的工作原理,尽管有时甚至超越了我。
首先要注意的是,每个PassportStrategy
必须扩展抽象混合输入PassportStrategy
。此混入从常规护照包(在这种情况下为Strategy
)中提取passport-jwt
。该策略具有默认名称(此处为jwt
),但是您可以传递第二个参数来提供您自己的名称。
Nest做一些非常酷的魔术,将CustomStrategy
的构造函数的super()
调用中的值传递给护照正常注册。然后,它使用CustomStrategy#validate
并将其应用于护照的验证回调,这就是validate
方法必须必须匹配护照的预期verify
回调的原因。
现在我们已经完成了一些护照注册,但是要正确调用这些护照,我们需要研究AuthGuard
mixin。通常,我们可以将策略传递给mixin,并且该策略需要匹配护照策略的名称(在这种情况下,例如jwt
),也可以在PassportModule
的{{1}中进行设置} 选项。从这里,后卫做了一点魔术,以按名称(defaultStrategy
,jwt
,google
等)调用该策略,并传递了local
, 1}}和request
从Nest创建的http上下文中创建。在调用结束时,response
由next
返回的值设置。