Refresh Token Rotation and Reuse Detection in Node.js JWT Authentication

Refresh Token Rotation and Reuse Detection in Node.js JWT Authentication

Dave Gray

2 года назад

60,614 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Royal Whales
Royal Whales - 05.10.2023 06:01

Hi Dave! Please consider this scenario :
User A login using Device A = Acces Token(A) = OK, Refresh Token(A) = OK
User A login using Device B = Acces Token(B) = OK, Refresh Token(B) = OK
User A requests tokens using Device A = Acces Token(C) = OK, Refresh Token(C) = OK
User B tries to access resources using the expired Refresh Token (A) --> Reuse Detection --> All Refresh Token Deleted (OK)

Here is the loop beginning:

User A requests tokens using Device A by Using Refresh Token C (Deleted) --> Reuse Detection --> All Refresh Token Deleted (OK)
User A login using Device A = Acces Token(D) = OK, Refresh Token(D) = OK
User A requests tokens using Device B by Using Refresh Token B (Deleted) --> Reuse Detection --> All Refresh Token Deleted (OK)
and so on... Reuse Detection Loop

Ответить
A
A - 02.09.2023 19:49

Been following this series (which have been great, thank you so much for all these tutorials!), and I had a question regarding this architecture: What if I had a situation wherein a user's account is compromised and I needed to log that user out immediately ? The refresh token would be simple enough: just clear all the user's refresh tokens from the database and mark the user's account as "banned"/"inactive" and prevent banned/inactive users from logging in. However, with the way it's setup in this course, the access token could potentially still be good for a few more minutes and since the verifyJWT middleware only checks the access token , the user could still access secure endpoints for the duration of the access token's life.

You briefly mentioned the possibility of storing the access token in the database, but said that'd be significantly more work and calls to the DB. Is that the only way to revoke an access token? Or is there some other way of handling this situation?

Ответить
Deadeye
Deadeye - 30.08.2023 19:02

So can you explain 2 things
1. why store in memory? when doing hard refresh memory is removed, so how will i get access token?
2. How does deleting refresh token from user db will fix if someone else using that refresh token, so you mean on each request i need to check DB if that refresh token exist if not logout user?

Ответить
tho rw
tho rw - 15.08.2023 09:52

How can I implement idle timeout (user inactivity) using jwt token ?

Ответить
Plínio Júnior🇷🇺
Plínio Júnior🇷🇺 - 12.08.2023 02:48

Wouldn't issuing a new refresh token every time we issue a new access token just grant indefinite access? If my refresh token is set to expire in 24 hours i could postpone its expiration by accessing a protected route and issuing a new refresh token, which would grant me additional hours and then i could just repeat the process ad infinitum.

Ответить
Aleksandr Petrov
Aleksandr Petrov - 10.08.2023 13:09

I'm getting error on backend connected with version of document.
VersionError: No matching document found for id "64d245663fcb09a41d999fae" version 45 modifiedPaths "refreshToken"
It happens in refreshTokenController. I've seen suggestions to use update method for model instead of save. But it doesn't exist )) Looks like findOneAndUpdate method should be used there. Which will change the controller code because we have to find user and update in the same place

Ответить
Mahesh Jarange
Mahesh Jarange - 14.07.2023 15:52

refresh_token_rotation/blob/main/controllers/authController.js : Line - 55. I think user getting logged out from all devices.

Ответить
Serhii
Serhii - 14.07.2023 12:17

Hi! Sorry for this comment, but I think your code is a complete disaster.
I really believe that you shouldn’t teach people to create such a code.
Let me explain.
Take a look at any of your controllers. Have you ever heard about the Layered System (structure), which says that: ”An application architecture needs to be composed of multiple layers. Each layer doesn’t know anything about any other layer”?
In your controllers you have a mixture of Transport layer (req, res), Business Logic Layer (BLL), Data Access Layer (DAL). And of course all the jwt stuff should be extracted into middleware.
And I guess everybody should know that real world Node.js applications rarely use JS these days, please consider using TS instead.

Ответить
Nir Gluzman
Nir Gluzman - 12.07.2023 12:52

Great video, very comprehensive !!!

authController takes care of the Login process.
1) Why don't you include the accessToken in the cookies, but rather in body?
2) It seems that the code does not handle the scenario where a user logins with a valid refreshToken belongs to a different user. The new accessToken array is not affected, but would it be a concern?

logoutController - concerning the scenario where refreshToken is invalid. (refreshToken is not in db).
How should we handle this case, only by sending 204?

Ответить
Infernal Coder
Infernal Coder - 12.06.2023 14:15

If refresh token has 15 minutes window, It means that the user has to log in again if he doesn't use token in 15 minutes, And if he does, then a new refresh token will be sent with new 15 minutes window, Am I right? What methods is used by apps like Instagram so user has to login only one time? It uses a token with a long expire date ?

Ответить
ForeverExpanding
ForeverExpanding - 10.06.2023 03:36

I have a scenario I am not quite sure if I have the best approach: access token in memory, cookie refresh token, but user refreshes page, hence loses access but still has cookie to refresh. Do I just check every time someone logins if they have a cookie, by calling the refresh token API? Is there a better approach to this? Thanks

Ответить
Riad Hossain
Riad Hossain - 03.06.2023 16:58

Dave I have a questions ⁉️ if I make two requests simultaneously Request A and B both with expired AT1 and RT1, server will invalidate the pair for request A but because B hass also attempted with the same pair, server will throw token reuse error in case of request B ! Resulting in a forced logout even the request was from the same trusted application how to handle this scene ?

Ответить
udit khandelwal
udit khandelwal - 29.05.2023 15:38

what if someone gets the refresh token and the legitimate user hasn't logged out or user hasn't used the refresh token then the refresh token will be present in the array in database, then the hacker will get the access token while logging in so how to stop the hacker to log in how to be secure in this way?

Ответить
Abdullah shaban
Abdullah shaban - 26.04.2023 23:43

amazing man thanks for the great tutorial . u've earned a subscriber . love u keep up the good work. will also buy u a coffee :*

Ответить
Micael Die
Micael Die - 10.04.2023 05:59

Thank you very much, you are the best! real-life technique in the tutorial your series it's GOLD

Ответить
lyes bennai
lyes bennai - 17.03.2023 18:19

first of all, thank you dave, I think there's a hint in your last point addition => if someone stole you refresh token, and he use is to generate a new access token, I think it is possible

Ответить
M&P basics
M&P basics - 15.03.2023 19:25

this is simply the vest

Ответить
krish goku
krish goku - 06.02.2023 19:34

hello sir hope you are well .....my qus is i tried this code with axios interceptor in react js and its works fine but multiple get method with axios interceptor this code is not working well

Ответить
Matt
Matt - 02.02.2023 22:19

My problem is with multiple fetch requests on the same page; first request will refresh the tokens, then the following requests are using the original cookie and looking for a refresh token that no longer exists in the DB

Ответить
kimaya panash
kimaya panash - 29.01.2023 14:38

I don't understand the last minute addition part.
Can someone help?

Ответить
kimaya panash
kimaya panash - 29.01.2023 14:18

We clear the refresh token array in DB if token reuse is detected.
Wouldnt that remove the refresh token for all the users?
Even those whose refresh token isn't compromised?

Ответить
Shaktijeet Sahoo
Shaktijeet Sahoo - 20.01.2023 02:21

Hello! Thank you for this awesome tutorial. Though, I have an doubt regarding token reuse detection. Let's consider a scenario:

Entities: User, Hacker, Device 1, Device 2

1. Hacker steals token from Device 1 and uses it.
2. User tries to use the same token on Device 1 and gets logged out by deleting all refresh tokens.
3. Now he logs in on Device 1 again using his credentials.
4. Next he tries to access the server from Device 2. Since the token from Device 2 isn't valid anymore, it'll fire reuse detection and again delete all refresh tokens, including the new one for Device 1.


This can go on for all the devices an user has logged in on. Any way to prevent this?

Ответить
pozz leng
pozz leng - 17.01.2023 07:14

themplate name?

Ответить
Thanga pandian
Thanga pandian - 11.01.2023 13:51

This Tutorial Full video link pls..

Ответить
Novianto
Novianto - 04.01.2023 09:45

Hi Dave, I have a problem when implementing this in my project. When I refresh my web, my app sends a request to refresh API 3 times, with the first successful and another failing (with console rT reuse). What do you think about this problem? Thanks. Edit: I fixed it with check the persist array dependencies and remove react strict mode.

Ответить
Wanderson
Wanderson - 31.12.2022 20:00

This is gold! Good job, DG! Happy new year!!!

Ответить
Awekening Bro
Awekening Bro - 13.11.2022 15:34

hi, this is to remark your statement on not to store tokens in local storage or cookies, I store my token in local storage and have seen other dev store in there as well, is it really bad to do so? if so why do people do it?

Ответить
Cool Programmer
Cool Programmer - 30.10.2022 19:53

cookies vs localstorge which is best??

Ответить
Tong Tony
Tong Tony - 26.10.2022 04:37

how get cookie in reactjs from nodejs? i read your reactjs program. I don't understand how get cookie from nodejs backend program. Is backend program send cookie to fontend program? So, we can see save cookie in chrome's application page. Thank you very much.

Ответить
Oscar Quinteros
Oscar Quinteros - 10.10.2022 21:04

I would love it if you could do this exact implementation with KOA.js. I could not figure out how to do it with KOA and could not find examples or tutorials online.

Ответить
jerome
jerome - 08.10.2022 06:23

Hi Dave can you answer please ? RT detection might lead to infinite log in loop ?

What happens in this scenario :
- user log in on desktop AND phone
- Hacker stole desktop RT and uses it
- User attempts to use desktop RT but RT detection detects he used an old RT then it clears RT array
- User log in again on desktop
- Then user switches to phone and uses phone RT, but RT detection won't find this RT (as the array was cleared) and clear again the array token.
- He log in again on phone then switch to desktop
- he uses desktop RT but again the RT detection won't find it and clear the array token etc

I surely missed something. Thanks

Ответить
Kennedy Dre
Kennedy Dre - 06.10.2022 15:46

Hi Dave,

I have a problem. When the user logs in and I return the jwt cookie in the response cookies. When I refresh the browser the cookie is deleted and I cannot call the refresh token endpoint to get a new access token.

Am I meant to store the refresh token Cookie front end? Or how should I go about this? Thank you in anticipation of your response.

Ответить
Kennedy Dre
Kennedy Dre - 30.09.2022 13:03

This is the best tutorial I have seen on the topic. You're a great teacher, subscribed!

I do have a question; I find that my refresh tokens array on my model keeps growing because I don't have a way of deleting old refresh tokens that have expired. How would you handle that?

Ответить
Oscar Quinteros
Oscar Quinteros - 23.09.2022 18:13

I looked at this video and I am not sure at what point you call the refreshToken route. Is it the front end responsobility or the backend? Can you point me out to where that is implemented?

Ответить
Rabia Loukhai
Rabia Loukhai - 17.09.2022 21:14

♥️

Ответить
Jomar Amomas
Jomar Amomas - 06.09.2022 06:40

Great video as always man, really appreciate your hard work. Btw I have a question. Do you have any tips or techniques on how to effeciently clear up the refresh tokens records from the db. This list will grow and grow specially when refresh token expires, then the user will log in again, then will add new record of refresh token in the db.

Ответить
sein sein
sein sein - 03.09.2022 06:22

hi dave... ive been following your excellent tutorials and ive encountered a problem when accessing the frondend via different ip from the frontend & backend server ips. my backend wont receive my cookies for the refreshtoken api. in the frontend my axios baseUrl is set to the specific ip of my server so i can send request from a separate machine.

i had no problems using 'localhost' as baseUrl on the frontend and backend at my server machine tho but if i change it up to my server's ipv4, my refreshtoken api receives null cookie as well.
im developing this web app to run locally in my network.
any solutions for this? i would appreciate it very much.

Ответить
Marius GUISSOU
Marius GUISSOU - 02.09.2022 17:28

👍👍👍👍👍👍👍👍👍👍👍 very good tutorial

Ответить
Tadeo Bustamante
Tadeo Bustamante - 17.08.2022 06:19

Amazing series Dave! I already finished the React course and decided to check on this one to apply these concepts in my Python backend. I just have one quick question. Do you happen to know how the sessions would be cleared out from the database? Let's say the user uses a lot of "Incognito" mode in chrome to log into our app. This will create a Refresh Token each time they log out from a new Incognito window, or device. Eventually, their Refresh Token array in the DB will be filled out with a lot of sessions that will be all expired at some point. Would it be a good practice to have some sort of "cleaner" system in the backend to check and clear the expired Refresh Tokens? or Is there a better way to do it?

Thank you!

Ответить
Kev L
Kev L - 15.08.2022 20:36

Brilliant tutorial Dave! I added to this by offering a 'logout of all devices' option to my user account page and simply called a backend route that set the relevant user's refreshToken array to an empty array.

Ответить
Isaac Wise
Isaac Wise - 12.08.2022 07:50

Hi, could you maybe do a video about JWT vs sessions or a video creating an auth system with sessions?

Ответить