Nelson Teixeira
Nelson Teixeira

Reputation: 6580

Is there a way to differentiate a request rejection from a bad or non-existent token to a token expiration in NestJs Passport JWT?

I want to be able to differentiate the reason why my request was rejected in a NestJS Passport-JWT project.

Now it's returning "401 - Request failed with status code 401" (ERR_BAD_REQUEST) in both cases.

As I'm using passport with JwtStrategy it doesn't pass through validate function in these cases.

How can I differentiate between the 2 and return which one it is to the client ?

Edit

I tried to look at the source code. Maybe I could extend AuthGuard. But the real authentication is made my Passport. But it wasn't clear to me where is the authentication method.

I found one at NestJs/Passport project, another in JwtStrategy and another in jaredhanson/passport project. But none seem to do the real authentication.

Upvotes: 1

Views: 385

Answers (1)

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12373

You can create your own decodeToken function, similar to this:

//import jwtservice in your constructor 
(private readonly jwtService: JwtService){}


 public async decodeConfirmationToken(token: string) {
    try {
      const payload = await this.jwtService.verify(token, {
        secret: 'IMPORT_YOUR_SECRET_HERE'),
      });

      if (typeof payload === 'object' && 'email' in payload) {
      //im returning email, because I need it in reset password function.
        return payload.email;
      }
      throw new BadRequestException();
    } catch (error) {
      if (error?.name === 'TokenExpiredError') {
        throw new BadRequestException('Reset password token expired');
      }
      throw new BadRequestException('Bad reset password token');
    }
  }

Upvotes: 0

Related Questions