I'm trying to secure a nestjs api project using a jwt generated by google oauth. I have the client code working and have verified with jwt.io that the jwt being generated is correct and validates ok with the client secret I have.
I have followed the guide from nestjs for implementing passport and the jwt auth guard, however all I get when I pass a bearer token to an method with the guard is JsonWebTokenError: invalid algorithm
The relevant code snippits:
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 {}