W
W
WebLedNik2021-04-14 22:03:28
Node.js
WebLedNik, 2021-04-14 22:03:28

How to add custom events on JWT validation errors via passport-jwt NestJs?

I am new to Nest js.

Problem:
I'm trying to add a cookie delete event to a jwt in case the jwt is invalid.
There is a solution to set equal lifetime jwt and cookie.
But I would like to add this event for jwt validation errors.
As I understand it, this block is responsible for jwt validation in passport-jwt.

import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { PassportStrategy } from "@nestjs/passport";
import { Request } from "express";
import { ExtractJwt, Strategy } from "passport-jwt";

const configService = new ConfigService

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([(request: Request) => {
        return request?.cookies?.jwt
      }]),
      ignoreExpiration: false,
      secretOrKey: configService.get('JWT_SECRET_KEY')
    })

  }

  async validate(payload: any) {
    return {
      id: payload.id,
      firstName: payload.firstName,
      lastName: payload.lastName,
      email: payload.email
    }
  }
}


And when we successfully pass the validation, the validate function is called. But when an error occurs while checking jwt, then a 401 response comes from the server. And the question arises, how to add a cookie deletion event?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question