cia*_*ius 5 nestjs nestjs-passport
我正在尝试使用 google oauth 生成的 jwt 来保护 Nestjs api 项目。我的客户端代码可以正常工作,并且已经通过 jwt.io 验证了生成的 jwt 是否正确,并且使用我拥有的客户端密钥进行了验证。
我已经按照 Nestjs 的指南实施护照和 jwt 身份验证防护,但是当我将不记名令牌传递给带有防护的方法时,我得到的只是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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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 {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1086 次 |
| 最近记录: |