Search code examples
jwtpassport.jsnestjsnestjs-passport

NestJS & Passport: Change JWT token on user password change?


I'm trying to reset/change the token (JWT) for users who changed their passwords on NestJS API with PassportJS. Here is a clean example of how this authorization works: https://docs.nestjs.com/security/authentication.

I want to generate a new token on password change to make sure, that on every device on which the user was logged in, after password change they will get unauthorized and so logged out.

This is how I handle the password change in users service:

async changePassword(uId: string, password: any) {
    return await this.userRepository.createQueryBuilder()
      .update(User)
      .set({ password: await bcrypt.hash(password.value, 10) })
      .where("userId = :userId", { userId: uId })
      .execute();
  }

There are no prebuild methods to do this I think. JwtService got only 5 methods: decode, sign (this one is used to generate a token), signAsync, verify and verifyAsync.

So how can I do this properly?


Solution

  • You'd need some sort of way to invalidate the JWT that was already given to the user. As you can't just do that to a token, generally (it's stateless, it holds its own validity) you'd need to create a JWT restrictlist in a database that you check the incoming JWT against. If the JWT is in the restrictlist, reject the request. Otherwise, let it through (if it's valid of course)