5

I'm using JWT passaport to login module:

 async validateUser(userEmail: string, userPassword: string) {
    const user = await this.userService.findByEmail(userEmail);
    if (user && user.password === userPassword) {
      const { id, name, email } = user;
      return { id: id, name, email };
    }else {
      throw new UnauthorizedException({
        error: 'Incorrect username or password'
      });
    }
  }

  async login(user: any) {
    const payload = { email: user.email, sub: user.id };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }

This part is running. My question is: how do the logout? I read about creating a blacklist and adding the token to it, but how do I get the user's access token?

KargWare
  • 1,746
  • 3
  • 22
  • 35
Juan Carlos
  • 53
  • 1
  • 1
  • 3

7 Answers7

14

Something you should know about token-based authentication is that it is stateless. This means that even the server does not keep track of which users are authenticated, like with session-based authentication. As such, you do not need to do anything on the server side to "log out" a user. You simply need to delete the t\JWT token on the client. If you make a request to the server app, without a valid JWT token, it will be treated as the user is not logged in.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Patrick Lumenus
  • 1,412
  • 1
  • 15
  • 29
  • 3
    If you delete the token at client-side, that token is still valid and can be used by a malicious user who has copied it before! – Kreshnik Jun 18 '22 at 22:54
  • @Kreshnik JWT tokens expire extremely quickly. So, usually within minutes. So, the likelihood of a token being misused is very small. – Patrick Lumenus Jun 19 '22 at 23:28
  • The best solution for you is to set the token time to maybe 5 minutes and implement a refresh token that is valid for 7 days. Inside your refresh token generation logic, you can check in your database if that user still has the right to access your API or not before generating a new token for him – Yousi Jun 06 '23 at 04:38
1

Generally when a logout request would be sent the Authorization header should be present, so you can grab the token from there. Then you can save the token to the database's restrict list table.

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
1

When user click to "Log out" btn, you should sent a request which is attached Authorization header with bearer token. In the backend side, you need to extract header and push the token to the blacklist token (as your solution). Basically, you only need remove token in client side, it's so easy to do but in the worst case when the token was stolen by hacker, your token still valid. Using blacklist token is more secure but it can be lead to performance issue and scalable. What is the best solution? it's depend on you.

Sang Dang
  • 422
  • 2
  • 5
  • 13
0

Read the Nestjs Execution context get the token from the request header and verify this token from JWT.

everything defines in the NESTJS link

//here we check the token from the header is valid or not expired

const tokenVarify = await this.jwtService.verify(token);
0

my idea is make whitelist every generate new token and remove it when user logout. so u need to check on guard also every user with token access its exist on whitelist or note

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 07 '21 at 05:05
0

You must be refresh expire token to 1ms with: https://webera.blog/how-to-implement-refresh-tokens-jwt-in-nestjs-b8093c5642a9

Masoud
  • 332
  • 2
  • 9
0

Actually there is a workaround for this, but not so straightforward! The idea is to keep track of the tokens for logged out users (use some sort of black-list) and query provided token against that black-list.

To sum it up, you can follow these 4 steps:

  1. Set a reasonable expiration time on tokens
  2. Delete the stored token from client side upon log out
  3. Have DB of no longer active tokens that still have some time to live
  4. Query provided token against The Blacklist on every authorized request

For detailed explanations, you can check this post: medium

A guide in how to do the implementation is in this youtube video Code with Vlad , and there's as well the github source nestjs-jwts. I followed this video and implemented myself as well..

Kreshnik
  • 2,661
  • 5
  • 31
  • 39