我正在尝试使用由 google oauth 生成的 jwt 来保护 nestjs api 项目。我让客户端代码正常工作,并使用 jwt.io 验证生成的 jwt 是正确的,并且使用我拥有的客户端密码验证正常。
我已按照nestjs 的指南实施护照和jwt auth 保护,但是当我将不记名令牌传递给带有保护的方法时,我得到的只是JsonWebTokenError: invalid algorithm
相关代码片段:
jwt.strategy.ts
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: true,
secretOrKey: privateKey,
algorithms: ['HS256']
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async validate(payload: any) {
const user = await this.authService.validateUser(+payload.sub);
console.log(user);
return user;
}
}
jwt.auth-guard.ts
export class JwtAuthGuard extends AuthGuard('jwt') {
handleRequest(err, user, info, context) {
// valid Token: empty log line
// invalid Token: empty log line
console.log(err, 'error');
// valid Token: token object
// invalid Token: false
console.log(user, 'user');
// valid Token: empty log line
// invalid Token: error object from passport
console.log(info, 'info'); <---- ERROR COMES FROM HERE
// valid Token: no log line at all
// invalid Token: no log line at all
console.log(context, 'context');
if (err || !user) {
console.error(`JWT Authentication error: ${err}`);
throw err || new UnauthorizedException();
}
return user;
}
}
auth.module.ts
imports: [
PassportModule.register({ defaultStrategy: 'jwt', session: true }),
JwtModule.register({
secretOrPrivateKey: privateKey,
signOptions: {
expiresIn: 3600,
algorithm: 'HS256'
}
}),
UsersModule
],
providers: [AuthService, JwtStrategy],
exports: [AuthService]
})
export class AuthModule {}