I have implemented a jwt authentication in nestJs. However whenever I attempt to authenticate using the following authorization headers:
Bearer <token> or JWT <token>
I got 401. These are my authentication files
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: `${process.env.SECRET}`,
});
}
async validate(payload: Credentials) {
const user: Account = await this.authService.validateAccount(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
handleRequest(err, user, info) {
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
}
and this my auth module
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: `${process.env.SECRET}`,
}),
AccountModule,
],
providers: [AuthService, JwtStrategy],
controllers: [AuthController],
exports: [PassportModule, AuthService],
})
export class AuthModule {
}
validate
will only be called when you pass a valid jwt token. When the token is signed with a different secret or is expired, validate
will never be called. Make sure you have a valid token. You can check your token for example with the jwt debugger.