In NestJS and passport, how do I create an endpoint that accepts a valid or invalid JWT?

35 views Asked by At

I'm using NestJS 10 with passport-jwt. I have a controller method in which the user can access whether or not they include a valid JWT in the Authorization header. If they include a JWT, I would like to know who the user is

  @UseGuards(OptionalAccessTokenGuard)
  @Post('paymentIntent')
  createPaymentIntent(
    @Req() req: Request,
    @Body() createOrderDto: CreateOrderDto,
  ): Promise<PaymentIntent> {
    const userId = req?.user['sub'];
    return this.ordersService.createPaymentIntent(userId, createOrderDto);
  }

The guard I have is defined as such

@Injectable()
export class OptionalAccessTokenGuard extends AuthGuard('jwt') {
  async canActivate(context: ExecutionContext) {
    await super.canActivate(context);
    return true;
  }
}

THe problem is, if the user submits an invalid JWT (it has expired or there is some other problem), this method returns a 401. How can I adjust the guard or method such that submitting an invalid or expired JWT will still allow the method to proceed, only that the user ID is not obtained?

1

There are 1 answers

0
Jay McDoniel On BEST ANSWER

Add a try/catch around the super.canActivate, so that if it throws an error it can still return true