Search code examples
authenticationjwtnestjspassport-jwt

Customise the response on verification failure for a jwt Strategy NestJs


I successfully implemented a jwt strategy for authentication using nestJs.

Below is the code for the jwt strategy

import { ServerResponse } from './../helpers/serverResponse.helper';
import { Injectable, UnauthorizedException, HttpStatus } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { config as env } from 'dotenv';
import { Bugsnag } from '../helpers/bugsnag.helper';

env();

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
    constructor(
    private readonly logger: Bugsnag,
    ) {
    super({
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
        secretOrKey: process.env.JWT_SECRET_KEY,
        passReqToCallback: true,
    });

    }

    async validate(payload, done: Function) {
    try {
        const validClaims = await this.authService.verifyTokenClaims(payload);

        if (!validClaims)
            return done(new UnauthorizedException('invalid token claims'), false);
        done(null, payload);
    } catch (err) {
        this.logger.notify(err);
        return ServerResponse.throwError({
        success: false,
        status: HttpStatus.INTERNAL_SERVER_ERROR,
        message: 'JwtStrategy class, validate function',
        errors: [err],
        });
    }
    }
}

I saw here that the validate function will be called only when a valid token was provided in the request headers and I'm okay with that. However, I would like to know if it is possible to customize the response object which is sent in that case (invalid token provided).

If yes, how do I do that ?


Solution

  • You can use a exception filter to catch UnauthorizedExceptions and modify the response there if you'd like. The other option would be extending the AuthGuard('jwt') mixin class and adding in some logic around a try/catch for the super.canActivate(context), then in the error read what the reason is and throw a specific UnauthorizedException with your custom message