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

  Рет қаралды 61,456

Dave Gray

Dave Gray

Күн бұрын

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
Node.js JWT Authentication is leveled up when you add refresh token rotation and reuse detection. We'll also be adding support for multiple logins / devices to the an existing REST API in Node JS.
🚩 Subscribe ➜ bit.ly/3nGHmNn
🔗 Starter Source Code: github.com/gitdagray/mongo_as...
🔗 Completed Source Code: github.com/gitdagray/refresh_...
🔗 Node JS Full Course for building the REST API: • Node.js Full Course fo...
🔗 React Login Authentication Series: • React Login, Registrat...
📬 Course Updates ➜ courses.davegray.codes/
Node.js JWT Authentication, Refresh Token Rotation and Reuse Detection
(00:00) Intro
(00:12) Welcome
(00:40) Refresh Token Rotation Explained
(02:26) Multiple Device / Login Support
(04:03) Refresh Token Reuse Detection
(11:08) Refresh Controller
(16:50) Logout Controller
(17:46) Auth Controller
(21:09) Verify logout deletes refresh token
(22:31) Delete an old token at login
(24:46) Identify an expired refresh token
(27:09) Confirm refresh token reuse detection
(30:59) Check multi device / login support
(32:32) Last Minute Addition: An important scenario
☕ Buy Me A Coffee: www.buymeacoffee.com/davegray
TLDR: Nothing in the browser is 100% completely secure. We just secure it as best we can.
Postman: www.postman.com/downloads/
📚 Refresh Token Rotation and Reuse Detection References:
Refresh Token Rotation at Auth0: auth0.com/docs/secure/tokens/...
Refresh Token Rotation (LogRocket): blog.logrocket.com/persistent...
Is Refresh Token Rotation Really Enough?: stackoverflow.com/questions/6...
📚 JWT References:
Intro to JSON Web Tokens: jwt.io/introduction
All You Need to Know About Storing JWT in the Frontend: dev.to/cotter/localstorage-vs...
NPM jsonwebtoken package: www.npmjs.com/package/jsonweb...
NPM cookie-parser package: www.npmjs.com/package/cookie-...
Deleting Cookies: expressjs.com/en/api.html#res....
Cross-Site Scripting (XSS): owasp.org/www-community/attac...
Cross-Site Request Forgery (CSRF): owasp.org/www-community/attac...
REST Security Cheat Sheet: cheatsheetseries.owasp.org/ch...
👀 Visual Studio Code: code.visualstudio.com/
✅ Follow Me:
Github: github.com/gitdagray
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this Node.js JWT Auth tutorial about refresh token rotation and reuse detection helpful? If so, please share. Let me know your thoughts in the comments.
#refresh #token #rotation

Пікірлер: 209
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Applying refresh token rotation takes your JWT auth strategy to the next level. You will no longer have long-lived refresh tokens providing access to resources if the tokens are comprised. This refresh token strategy also pairs well with refresh token reuse detection. In this tutorial, we will apply both refresh token rotation and reuse detection to the Node JS REST API built in my Node JS for Beginners full course. If you haven't completed that Node JS course yet, I recommend starting with it here: kzbin.info/www/bejne/nGOoonh5nrl1gpo
@donvercety
@donvercety 2 жыл бұрын
Hi there, I think when you introduced arrays for the refresh token... you also introduced a race condition when manipulating this refresh tokens...? Where you read, manipulate and then save the token array.... what about concurrent requests doing the same thing on the same user..? Am I missing something here...?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
​@@donvercety this could be a consideration worth testing. To create this condition, you are suggesting two attempts to login simultaneously if I understand correctly. Please let me know what you discover. 💯
@donvercety
@donvercety 2 жыл бұрын
​@Dave Gray I did a basic test and indeed accomplished the race condition. The result was not a corrupt data in DB, coz MongoDB do have some safety checks when this type of situation occurs. It ended up throwing an uncaught error. But when I try to explain how to reproduce with examples my comment gets removed, don't know why. :(
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
​ @donvercety KZbin has been randomly removing viewers comments which is frustrating. No rhyme or reason to it. Maybe share with a gist?
@donvercety
@donvercety 2 жыл бұрын
@@DaveGrayTeachesCode tried to use "pastebin", with no luck... will try again next couple of days :). Nevertheless - awesome tutorial.
@kevl7129
@kevl7129 Жыл бұрын
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.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! That sounds like a great addition! 💯
@RahdixCloudNine
@RahdixCloudNine 9 ай бұрын
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
@willyhorizont8672
@willyhorizont8672 2 жыл бұрын
woah I thought the jwt part is done but there's more. thanks again Dave, currently watching I hope I can follow along implement this in my app.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You've got this! Don't miss the last minute addition at the end. 🚀
@jessbk1678
@jessbk1678 2 жыл бұрын
Simply one of the best tutorials on youtube
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Javed! 💯
@jovan4614
@jovan4614 2 жыл бұрын
WOW! Not that many videos i will watch few times but this one definitely.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! Glad it helped! 🙏🚀
@user-kf5ks6un7b
@user-kf5ks6un7b 4 ай бұрын
Thank you so much for this helpful playlist! I watched all the videos, and they provided me with valuable insights and knowledge that I needed. Great content!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 4 ай бұрын
Glad it was helpful!
@pinwanrj
@pinwanrj Жыл бұрын
This is gold! Good job, DG! Happy new year!!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! Happy New Year to you, too!
@dindoleonard
@dindoleonard 2 жыл бұрын
You deserve all the medals my good ser, if you create any courses I will surely buy or donate some. You are tackling important aspects that is very useful for any project in very exquisite detail.
@dindoleonard
@dindoleonard 2 жыл бұрын
I'll buy you a coffee in your link. Thank you so much.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Leonardo! 🙏🙏
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I appreciate the kind words, Leonardo! 💯
@NicolasRoehm
@NicolasRoehm 9 ай бұрын
Thank you very much for this excellent tutorial, and of course, for the linked source code, which helps me understand everything at my own pace !
@micaeldie8584
@micaeldie8584 Жыл бұрын
Thank you very much, you are the best! real-life technique in the tutorial your series it's GOLD
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're very welcome!
@Frankitoact
@Frankitoact 2 жыл бұрын
Hey Dave! Your tutorials are awesome! You're a great teacher. Just to know, Are you planning a nextjs series with the newest features? Again congratulations for such an amazing job. Greetings from Argentina!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words, Franco! And great to hear from Argentina! 💯 I am planning to work on a NextJS series later this year and it will be as up-to-date as possible. 🚀
@jejepro2629
@jejepro2629 8 ай бұрын
Thank you Dave ! It works great, but I need to understand a little thing. At the login, if there is no cookie with the value of the current refresh token, the tutorial updates the database by keeping the old refresh tokens and adding the one that has just been created at login. Thus, for each manual deletion of cookies, another refresh token is added to database. (5 manual deletion before login = 5 refresh tokens in database. What I need to understand is, do you think there is a reason to stock all of them ?
@nirgluzman1343
@nirgluzman1343 Жыл бұрын
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?
@Clash-Roblox
@Clash-Roblox 8 ай бұрын
Excuse me sir! I don't get when we clear the refresh token array. What is the affect to the user, when we only clear token in our database.
@co_bby
@co_bby 2 жыл бұрын
You are one of the best teachers out there. You explain things like a professor. Did you do education as a major in school?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you. 🙏 I have been teaching university courses for most of the last decade.
@Shuyinz
@Shuyinz Жыл бұрын
@@DaveGrayTeachesCode I wish you were my teacher when I was student back then!
@ryant2350
@ryant2350 2 жыл бұрын
Another amazing tutorial! Thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Ryan! 💯
@shibleesaidul4963
@shibleesaidul4963 2 жыл бұрын
Hi Dave, Thanks for your awesome tutorials. I found your tutorials really explicit. I learned a lot things from your tutorials specially on JWT. By the way just to be clear ,in refresh controller section @ 12.36 minute, condition in if statement should be if(err && user.id === decoded.id) instead of If(err) or condition in second if statement (err && user.id !== decoded.id) instead of (err || user.id !== decoded.id). as if(err) and (err || user.id !== decoded.id) evaluates the same ,if I am not wrong on this point.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Shiblee! 🙏 You could be right on that! When I get time, I'll re-evaluate. Thanks for the note!
@rajvardhansinghbirani1919
@rajvardhansinghbirani1919 2 ай бұрын
@Winter_Wyvern1 I too had the same thing in mind.
@UrosTripunovic
@UrosTripunovic 3 ай бұрын
Where is the register endpoint used? How can i ensure that a refresh token is changed after each request?
@thorw2136
@thorw2136 11 ай бұрын
How can I implement idle timeout (user inactivity) using jwt token ?
@WongYamPan
@WongYamPan Жыл бұрын
Hi Dave, thank you for the excellent React and Node youtube series on refresh token and refresh token rotation. Your series is fantastic! They are the best and most in-depth I have seen on KZbin and Udemy on JWT authentication. I have a question, and I apologise for the long post in advance. Based on your tutorial, 1) Upon the expiry of the initial auth token (at 1.0), the backend will check if the refresh token (rt 1.0) appears in the refreshToken[] (in the userSchema). If it appears in the refreshToken[], the backend will then generate a new auth token (at 1.1) in json + refresh token (rt 1.1) via httpOnly cookie and return to the frontend 2) The refresh token will always have the same expiry (e.g. one day) after it is re-issued. 3) Once the refresh token is re-issued, the backend will remove the expired refresh token (rt 1.0) from the refreshToken[] and add the new refresh token (rt 1.1) into refreshToken[] for the next verification. 5) If a hacker uses an old refresh token to authenticate (i.e. valid refresh token but does not appear in refreshToken[]), the backend will empty refreshToken[]. This will force all logins (belonging to this user) on other devices to re-login. 6) If there is no hacker and the user does not validate with the new auth token (at 1.1), the new refresh token (rt 1.1) will expire based on the expiresIn key in the jwt.sign() method ------- Am I correct to say that a potential vulnerability exists when a hacker gets hold of the refresh token (rt 1.1) and refreshes it to rt 1.2 upwards (before rt 1.1 expires), AND the valid user does not use the (rt 1.1) to authenticate (triggering an empty array in the refreshToken[])? E.g. A valid user (employee) who last refreshes the refresh token (rt 2.0) on Friday at 7 pm, and the refresh token is valid for 24 hours. As long as the hacker gets the refresh token (rt 2.0) and refreshes it (to rt 2.1 onwards) before Sat 7 pm (assuming no work over the weekend), the hacker will have valid access until the user try to auth with the token (rt 2.0). In fact, if the machine is stolen/harddisk formatted, the valid user will not be able to authenticate (with rt 2.0). Hence, the hacker will get infinite access by renewing the refresh token (rt 2.1 upwards) before its expiry. I have thought of 3 potential enhancements that would reduce (not remove) the risk, and I would love to have your input. 1) Implement a log out everywhere button where the backend will set an empty array to the refreshToken[] (in the userSchema). User will have to clear all cookies in all other logged-in devices and log in again (to prevent an endless loop of the cookie, as mentioned by Glacial in the previous posts) 2) The refresh token will have a shorter expiry time (e.g. 1 hr), so the refresh token will be invalid 1 hour after no authentication is made. This leaves a smaller window for a hacker to have a valid refresh token 3) All subsequence refresh tokens will have a shorter expiry time than the initial refresh tokens. For example -> backend generates initial refresh token (rt 1.0) at 1 pm with an expiry of 2 hrs -> Backend re-generates refresh token (rt 1.1) at 1.10 pm with an expiry of 1hr 50 mins -> Backend re-generates refresh token (rt 1.2) at 1.17 pm with an expiry of 1hr 43 mins This will require more coding. We need to store the expiry time (e.g. 2 pm) in the jwt payload, calculate the remaining time to expiry time, and set it as the expiresIn in the next refresh token. This ensures that the hacker will not be able to renew the refresh token indefinitely even if the log out everywhere button is not pressed. Let me know what you think, and thank you for the awesome tutorials!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Wow, I appreciate your detailed post! 💯 It is more than I have time to digest and reply to right now. Might I suggest you join my Discord where deeper discussions can take place? Dedicated viewers answer questions and converse there daily: discord.gg/neKghyefqh
@pliniojr95
@pliniojr95 11 ай бұрын
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.
@vladimirjovanovic3540
@vladimirjovanovic3540 5 ай бұрын
You are excellent teacher!!!!
@kimayapanash8998
@kimayapanash8998 Жыл бұрын
I don't understand the last minute addition part. Can someone help?
@uditkhandelwal6330
@uditkhandelwal6330 Жыл бұрын
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?
@henrikskarbrandt
@henrikskarbrandt 2 жыл бұрын
Thanks again Dave! This series keep geting better and better. One question: Doesn't these changes create a situation where the time limit on the refesh token is extended more or less indefinitely (if continuously refreshed)? Maybe this is acceptable or maybe should the new refresh token keep the expire date of the original? Am I overthinking this? Any thoughts?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
If the refresh token is continually refreshed, yes. That's why reuse detection is added with the token rotation. Likewise, it can still expire if not refreshed. The worst case scenario: A user logs in, does not use the refresh token, does not manually log out, and the refresh token is stolen. It could theoretically be renewed until the user either logs in again or attempts a request with the token they received. This scenario is addressed in the last minute addition section of the video. Overall, this is still considered better than simply issuing a refresh token that will expire in 24 hours as it would provide access until expired and all of those other things have to fall into place for the worst case scenario.
@tecneto
@tecneto Жыл бұрын
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!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Good question! And yes, it would be good to have a "clean up" function in there. Awhile back, someone asked a similar question. You may find that discussion here in the comments, too.
@ThomazMartinez
@ThomazMartinez 10 ай бұрын
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?
@user-gt2jd6km2w
@user-gt2jd6km2w 2 жыл бұрын
Thanks for great lecture Dave. I have a question. Does the token string(=jwt value) in the cookies disappear after the expiration date? We specified the case when an error occurred due to callback of jwt.verify() in the refreshTokenControlle.js file. However, the first parameter(="refreshToken") of jwt.verify() is a string stored in the cookie, and I wonder it is just string type, and how we could know that refreshToken is expired.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Good questions! Tokens do have an expiry value that you can see when decoded. Paste your token into the encoded window at this site: jwt.io/ ..you will see the decoded info on the right. You can also learn more about JWT structure here: jwt.io/introduction
@xingfucoder2627
@xingfucoder2627 3 ай бұрын
Hi Dave, great video as always🚀, could you make some extension for this video wit NestJS or Redis for manage tokens rotation and revocation?
@VictorSilvaDev
@VictorSilvaDev 2 жыл бұрын
Great video bro
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you!
@becbelk
@becbelk 2 ай бұрын
very exciting...
@LazyDali
@LazyDali Жыл бұрын
Thanks for this lecture. Very clear. Would you recommend using Redis for storing refreshTokens instead (due to the database transaction on every Http calls) or would it be overkill and premature optimization?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I would need to research your question more to give you a confident answer. If not using refresh token rotation and re-use detection, you can use JWTs without a database transaction - aka stateless - which many list as one of their strong points. Suggesting this as an option if database transactions are a concern.
@mohamedyoussef8835
@mohamedyoussef8835 2 жыл бұрын
Awesome +++ You are one of the best teachers out there +++++++++++++++++
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words! 🙏
@kennedydre8074
@kennedydre8074 Жыл бұрын
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?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great question and discussed in a few comments here if you want to browse them. I suggest putting in a process that deletes the old ones after a specified duration.
@kennedydre8074
@kennedydre8074 Жыл бұрын
@@DaveGrayTeachesCode thank you for your response. I saw the comment, I think his approach is easier to implement and I have done so.
@abdullahshaban1545
@abdullahshaban1545 Жыл бұрын
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 :*
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you for the support!
@abdullahshaban1545
@abdullahshaban1545 Жыл бұрын
Man u also need to make tutorials for next js . Its on the boom
@ahmad-murery
@ahmad-murery 2 жыл бұрын
I like refactoring when it results in a more robust app, It's always easier to improve your app functionalities when your code is well structured, for multi-device/user testing and unless it's a browser compatibility issue, I tend to use Chrome's Incognito window when I only need one additional user, If another user is needed I use Chrome's guest profile, more than that, I add additional profiles (without linking them to accounts), Thanks Dave,
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Incognito mode is a great choice! Have a good day my friend! 💯🙏
@ahmad-murery
@ahmad-murery 2 жыл бұрын
@@DaveGrayTeachesCode You too my friend ⭐ I wish I can be more helpful but life is hard😥
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@ahmad-murery you are always helpful. I hope your difficulties pass and wish you the best.
@ahmad-murery
@ahmad-murery 2 жыл бұрын
@@DaveGrayTeachesCode Thank you
@bennailyes9303
@bennailyes9303 Жыл бұрын
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
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes, I believe this is discussed. Nothing is 100% secure in the frontend, but we make our best efforts. Keeping the refresh token in an httpOnly secure cookie does prevent it from being access by JavaScript in the frontend. Otherwise, we must depend on the expiry we set.
@avalon_321
@avalon_321 2 жыл бұрын
Nice tutorial!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 🙏
@sonamohialdin3376
@sonamohialdin3376 2 жыл бұрын
Amazing tutorial thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're very welcome!
@foreverexpanding
@foreverexpanding Жыл бұрын
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
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
My approach to login persistence: kzbin.info/www/bejne/aGiuloyhYpqpgNk
@aleksandrpetrov3938
@aleksandrpetrov3938 11 ай бұрын
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
@aleksandrpetrov3938
@aleksandrpetrov3938 11 ай бұрын
solved it like this: const result = await foundUser.updateOne({ refreshToken: [...newRefreshTokenArray, newRefreshToken] });
@asdasd-jg1re
@asdasd-jg1re Жыл бұрын
33:23 newRefreshTokenArray = []; gave me 'tried to assign to a constant variable' error when i logged in my app today
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
32:40 shows you need to use the let keyword with newRefreshTokenArray and not const.
@usmanshahid8529
@usmanshahid8529 Жыл бұрын
Sir i have a faced an issue in applying this strategy, and that is i have two use effect and there are two apis inside this like this useEffect(()=>{ const func1=async(){ await getData() } func1() ,[]) useEffect(()=>{ const func2=async(){ await getData2() } func2() ,[]) }) The problem is that after both useEffect call ,the http only cookie disappear and ,refresh token did not work .... Can you solve this ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Hello - this question is not about Tailwind CSS but is posted on a Tailwind CSS video? Please join my Discord to ask questions and post in the appropriate channel after you join: discord.gg/neKghyefqh Thank you!
@ahmedelgaidi
@ahmedelgaidi 2 жыл бұрын
very helpful Thanks:)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! 💯
@jerome3777
@jerome3777 Жыл бұрын
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
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Hi Jerome, I always try to answer. If this is a true concern, you could alter the configuration. Auth0 also has some good articles on this topic: auth0.com/docs/secure/tokens/refresh-tokens/refresh-token-rotation
@tongtony3880
@tongtony3880 Жыл бұрын
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.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
The backend Node.js server sets the cookie in the browser. Your frontend code does not handle it. Before attempting this tutorial, I recommend learning more about JWTs and the Node.js server in my course here: kzbin.info/www/bejne/nGOoonh5nrl1gpo
@imjust_a
@imjust_a 10 ай бұрын
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?
@imjust_a
@imjust_a 10 ай бұрын
One idea I just had was to either create middleware to check if the user's account is banned/deactivated and clear the cookie before the verifyJWT middleware, or to just add that to the verifyJWT middleware, itself.
@motdde
@motdde Жыл бұрын
Hello Dave, Thanks for making this video. How do you make the http only work for mobile?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome! http works the same for mobile. It is a protocol and not device specific.
@novianto2346
@novianto2346 Жыл бұрын
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.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes, React strict mode as of version 18 is usually the cause. Discussion and workaround if needed: kzbin.info/www/bejne/bmLJko2wpZZrhK8
@ejazmuneeb
@ejazmuneeb 2 жыл бұрын
hats off. you are a pro.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words, Muhammad! 🙏
@dharmeshgohil9375
@dharmeshgohil9375 2 жыл бұрын
Wow, very useful tutorial
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 🙏
@dharmeshgohil9375
@dharmeshgohil9375 2 жыл бұрын
Try to make some reusable components which is useful in many app oe website so we can use it
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@dharmeshgohil9375 good idea for React 💯
@mrfirstname578
@mrfirstname578 Жыл бұрын
hello dave tq. Are cookie can get in react native, flutter or native mobile aplication or we must send refresh Token from req.authentication in mobile?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I know React Native supports cookies. I would be surprised if the others did not.
@riadhossain5701
@riadhossain5701 Жыл бұрын
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 ?
@mhm13dev
@mhm13dev 4 ай бұрын
Your client side should only send 1 request for refresh token and await other requests until the refresh token request is resolved
@henry-chung
@henry-chung 5 ай бұрын
Can we apply the approach of this auth series for both mobile and web, or only for web?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 5 ай бұрын
It works for both.
@juhandvan
@juhandvan 2 жыл бұрын
Hi Dave, the first of all thank you so much then i have a question: After we change data type of refreshToken (in User Model) from String to [String]. So why can we have: const foundUser = await User.findOne({ refreshToken }).exec(); It doesn't seem right, does it ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Did you run the code? It's right: mongoosejs.com/docs/api.html#model_Model-findOne
@juhandvan
@juhandvan 2 жыл бұрын
@@DaveGrayTeachesCode thanks, I make a mistake. Sorry man
@awekeningbro1207
@awekeningbro1207 Жыл бұрын
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?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
People do it because it is easy, but it is not secure.
@shaileshdubey3175
@shaileshdubey3175 2 жыл бұрын
Can we use it protect multiple login from single account?? I requested you to do this and you did this. You are best of best. Thank you sir.👌👌
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Shailesh! 💯
@seinsein6382
@seinsein6382 Жыл бұрын
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.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I can only guess about what may be different than my code here, but I suggest ensuring that the secure: true flag is set on the cookie. In a localhost dev environment, we disabled that in my backend code for testing - it is commented out. If you didn't change that, then it won't work with https.
@seinsein6382
@seinsein6382 Жыл бұрын
@@DaveGrayTeachesCode i actually did set it to true as well. apparently, whats happening is during login, the api is not sending back the cookie or it did but due to cross-origin policy it wont set the cookie.
@kimayapanash8998
@kimayapanash8998 Жыл бұрын
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?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
There should only be one user per user account.
@nikital.9036
@nikital.9036 2 жыл бұрын
I thought a bit and realized that the requireAuth component is losing its meaning a bit. It will be more efficient to divide routes into 2 categories: for unauthorized and for authorized users. It's a bit silly to be able to login or signup an already authorized user 😃
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
That is definitely a possibility. You can apply routing as you choose.
@dhirajkafle47
@dhirajkafle47 2 жыл бұрын
masterpiece !
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words! 🙏
@kennedydre8074
@kennedydre8074 Жыл бұрын
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.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Refreshing your browser should not delete a cookie set by the REST API. Confirm that you are in fact receiving the cookie from the server before the refresh. Your refresh token should be stored in the secure, httpOnly cookie.
@kennedydre8074
@kennedydre8074 Жыл бұрын
@@DaveGrayTeachesCode I just observed that it’s because I commented out the secure option on the cookie to allow me work with it on postman. Lol. Silly me and I’ve been fighting with my computer for days now 😅
@alvesbernardino
@alvesbernardino 2 жыл бұрын
Hi Dave, fantastic job, should I use your strategy with a MSSQL sever?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You can. The choice of database should not impact the strategy.
@alvesbernardino
@alvesbernardino 2 жыл бұрын
@@DaveGrayTeachesCode You are top, another question, when you refresh the access token you send a new refresh with another day, won't this eventually make it ever lasting?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@alvesbernardino no, they will expire if not refreshed before the expiry. In addition to the explanation given near the beginning of this video, you can learn more in my other JWT videos, too.
@deathcrafter18
@deathcrafter18 Жыл бұрын
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?
@iwas23
@iwas23 9 ай бұрын
hey, are you manage to solve this issue?
@danieleliasarreagafranco5641
@danieleliasarreagafranco5641 2 жыл бұрын
Nice
@krishgoku8498
@krishgoku8498 Жыл бұрын
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
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Sounds like you are creating multiple requests in React due to React 18 strict mode. I discuss how to avoid that here: kzbin.info/www/bejne/bmLJko2wpZZrhK8
@krishgoku8498
@krishgoku8498 Жыл бұрын
@@DaveGrayTeachesCode thanks for the help sir
@chetanjain4616
@chetanjain4616 2 жыл бұрын
I love your videos but help me out here. You have made 7 authentication video using JWT or Auth0 and now this one, I am thinking of starting them but I don't see how to serialize them or even know what's the difference between them as most of them has axios in title which is just a fetching library
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Good question, and easy to answer: For the frontend React login, follow the order of my React Login series here: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd For the backend Node JS REST API, use the full Node JS course where the backend REST API is built chapter by chapter: kzbin.info/www/bejne/nGOoonh5nrl1gpo and then this video you have commented on is considered a bonus chapter after completing that course.
@mpbasics8285
@mpbasics8285 Жыл бұрын
this is simply the vest
@antonkulakoff
@antonkulakoff 2 жыл бұрын
how do you plan to delete unused refresh tokens?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Cookies with expiration dates in the past are deleted from the browser. If you are talking about the backend, you could track more data - date issued, ip address, anything you want - and run a process to clean it up. I didn't dive into that.
@Matt-db7ky
@Matt-db7ky Жыл бұрын
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
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Sounds like you need to await the response of the first request before sending the others. 🤔
@Abbylovesdon
@Abbylovesdon 8 ай бұрын
What about browser refreshes? It may be a bit if of an edge case, but I personally have a habit of clicking the browser refresh multiple times quickly and I’ve noticed this scenario/race condition (database token updated but refresh cookie didn’t get the chance to update). This has been driving me crazy and I can’t find any good solutions…
@abdu5822
@abdu5822 2 жыл бұрын
i hope you plan on adding Unit Testing for Nodejs playlist.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the request, Abdullah! 🙏
@mylastore
@mylastore Жыл бұрын
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?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
The frontend issues requests to any of the backend endpoints. So yes, the app on the frontend would issue a request to the refresh endpoint when needed.
@mariusguissou4282
@mariusguissou4282 Жыл бұрын
👍👍👍👍👍👍👍👍👍👍👍 very good tutorial
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! Cheers!
@isaac.wise06
@isaac.wise06 Жыл бұрын
Hi, could you maybe do a video about JWT vs sessions or a video creating an auth system with sessions?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great request, Isaac! 🙏💯
@RougeSam
@RougeSam 2 жыл бұрын
Can you build a front end to show us how logging in would work with users/admins
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Mentioned in the video - this React Login series does exactly what you are requesting: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@jomaramomas7682
@jomaramomas7682 Жыл бұрын
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.
@jomaramomas7682
@jomaramomas7682 Жыл бұрын
Ah probably, instead of storing refresh tokens as strings of array, store it as an array of objects with keys of "token" and "expDate", then everytime the user logs in, that is also the time we purge the list of refresh tokens that have already expired.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great answer to your question! You nailed it! 💯
@kennedydre8074
@kennedydre8074 Жыл бұрын
Thanks just what I needed. Was considering using Redis till I saw this.
@user-lx3hx8qb7q
@user-lx3hx8qb7q Жыл бұрын
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 ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Possibly. Many variations and auth services (Auth0, Clerk, etc) exist. This is just one example of creating your own to gain an overall idea of how auth can work.
@leoMC4384
@leoMC4384 2 жыл бұрын
I hate you so much: I'll have to change a lot of insecure things I have in this MERN project I'm working on now. You're amazing. 😁😁😁
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Ha! Thank you, Leonardo! 😂💯
@samkaykasheef6982
@samkaykasheef6982 2 жыл бұрын
what is the outcome of learning html, javascript, css, reactjs, and nodejs? What do I qualify for after learnin these languages? Please assist if you may
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Students that learn these skills are usually wanting to become web developers or learning how to be better web developers than they already are. Other goals could apply including learning for fun or passing a college course.
@samkaykasheef6982
@samkaykasheef6982 2 жыл бұрын
@@DaveGrayTeachesCode Awesome. Thank you so much so, you made it so simple and fun to study. Now Im glued to your courses. You are a blessing to some of us thank you so much
@mahendranath2504
@mahendranath2504 2 жыл бұрын
great tutorial dave👍👌🙌👏, One strategy, I would like to know let's say, users are only once login it should now ask login again, if 401 unauthorized occurs it should regain a new Refresh token and get the update the token, just like mobile apps once you logged it will not ask to log in again or Facebook, can please do a video or explain on that
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Mahendra! 🙏 This works as you described so no other video is necessary. You just need to extend the length of the tokens. Possibly set the refresh token to 24 hours. The access token is usually set a shorter duration - maybe an hour. The durations set for this tutorial a very short just for example purposes.
@mahendranath2504
@mahendranath2504 2 жыл бұрын
@@DaveGrayTeachesCode I have been waiting for you reply 🫡👍, but at some point of time refresh token will expires like after 24 hours, let say my app has auth that will do once and it shouldn’t show login at all, I have been fallowing your channel , it awesome 👏 😎 🤩
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@mahendranath2504 yes, it must expire at some point if they stop using it. If they continue using it, it will refresh. Facebook and others do the same thing.
@mahendranath2504
@mahendranath2504 2 жыл бұрын
@@DaveGrayTeachesCode thank you so much 😊 , really inspiring teacher
@mylastore
@mylastore Жыл бұрын
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.
@mylastore
@mylastore Жыл бұрын
Or I could pay you if you can figure out how to set cookies with KOA.js
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thanks for the request! I'm not familiar with it, but I'll look it up.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Ah! Looks cool - from the Express team: koajs.com/
@mylastore
@mylastore Жыл бұрын
@@DaveGrayTeachesCode YEP KoaJS is fully async. By the way, I figure out how to set cookies with KOA, for me it worked by setting secure: true, but had to run development with HTTPS, therefore, I install local SSLs and everything worked.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
@@mylastore that is true without KOA, too. The secure: true flag only works with https
@fullstack_projects
@fullstack_projects Жыл бұрын
cookies vs localstorge which is best??
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
My Node.js course has a dedicated discussion of JWTs and why I believe you should not store them in localStorage. Also supporting article references: kzbin.info/www/bejne/nGOoonh5nrl1gpo
@fullstack_projects
@fullstack_projects Жыл бұрын
@@DaveGrayTeachesCode i shared your channel my college group tq so much sir your video content really awesome.. I pray to God to bless you and your family today and throughout your life.
@maheshjarange5597
@maheshjarange5597 Жыл бұрын
refresh_token_rotation/blob/main/controllers/authController.js : Line - 55. I think user getting logged out from all devices.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Likely. This video is nearly 2 years old, but if I remember correctly, I wanted to log out all users if a token was stolen.
@maheshjarange5597
@maheshjarange5597 Жыл бұрын
@@DaveGrayTeachesCode It is logging out same user from all devices who is trying to use fake or stolen token
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
@@maheshjarange5597 correct. If someone tries to use their token, it logs everyone out if I remember correctly. You can follow some of the links in the description to better understand the concept if needed.
@maheshjarange5597
@maheshjarange5597 Жыл бұрын
@@DaveGrayTeachesCode Thank you, Overall Great Video 👍
@thangapandian2363
@thangapandian2363 Жыл бұрын
This Tutorial Full video link pls..
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
There should be a link to my Node.js course for Beginners in the description. Otherwise, this is the full video on this topic.
@loukhai
@loukhai Жыл бұрын
♥️
@kamalraturi
@kamalraturi 8 ай бұрын
Why would one return 403 to indicate auth-failure. I think it should be 401. 403 means one is not authorized to access the resource and re-auth wont help ( as described in 403 documentation on mozila dev docs). 401 means auth failure and re-auth would work. Why 403 is so popular among youtube dev channels?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 8 ай бұрын
I cannot speak for other YT devs. I agree that 401 is a good choice. The recommendation on this depends on what you read. Sources can be provided advocating for each.
@kamalraturi
@kamalraturi 8 ай бұрын
Thanks. Got your point. Your videos are sooooooo much helpful.@@DaveGrayTeachesCode
@pozzleng6328
@pozzleng6328 Жыл бұрын
themplate name?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I think you're asking which theme I'm using? If so, here's a short where I explain: kzbin.infodp4u1NNFhtE
@pozzleng6328
@pozzleng6328 Жыл бұрын
@@DaveGrayTeachesCode thank u guy!
@bothorsen4292
@bothorsen4292 2 жыл бұрын
This is a good instructional video, but all the code copying is quite sad. You really should refactor to functions instead of copying large chunks of code (for example, at 15.10). I would reject this merge request :)
@serhii5661
@serhii5661 Жыл бұрын
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.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Nah, you're not sorry 😆. I've published a popular TypeScript course since this video was published. If you check the date, you'll see it's nearly two years old. Easy to go back on tech videos and criticize/recommend changes 2 years later. Code organization is a highly opinionated topic. I could have focused more on that, but I was more focused on the concept of the video. It's free. Anyone who doesn't like my methods in any video can have a full refund. No fake apologies for criticism required.
@GlacialYtb
@GlacialYtb 2 жыл бұрын
Hi, I think I found a problem/loop with the logic of your refreshTokenController (multiple devices and token reuse detection) correct me if I'm wrong 1.Legitimate User logs 2 devices -> Device1 gets RefreshToken1 (R1.0) -> Device2 gets RefreshToken2 (R2.0) 2. Legitimate User uses R1.0 to get a new refresh token (R1.1) 3. Hacker tries to use R1.0 after Legitimate User generated the new one (R1.1) 4. Code detects reuse and deletes all tokens in array of Legitimate User 5. Legitimate User logs back with Device1 all good 6. Legitimate User goes on Device2 (still has R2.0) and the app tries to refresh the token but it got deleted earlier after reuse detection 7. Backend detects a valid token that is not in array anymore so detects reuse and deletes all tokens 8. Legitimate User logs back with Device2 all good 9. Legitimate User goes back on Device1 that tries to refresh tokens and again... since he logged with Device2 earlier, the token on Device1 is not in the array anymore and the backend detects reuse and deletes tokens. 10. Legitimate User goes on Device2 that still has token and clears tokens since his token is not in the array anymore. 11. infinite loop.... So... simply, this could make a loop of disconnecting one device every time you connect on the other one since when one device still has a refresh token (that is not in the array anymore) it will try to refresh it and triggers your reuse protection. I feel the only way to handle that would be to store old tokens and create token families. If an old token is used, just delete the token family of one device without touching the token family of another.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I follow what you are saying and I'm glad to see you really thinking through this tutorial and all of the possibilities! The code in the tutorial works, but I believe you have identified what we might call an "edge case" where specific things need to fall in place before it is ever experienced - although it could happen. To recreate this, a user needs to be logged in with at least 2 different devices and have someone steal a refresh token and attempt to use it before it expires which deletes all of the users refresh tokens. Further, they need to attempt to use at least two of their devices with their previous refresh tokens before the pre-existing tokens would expire. I do think this is a possibility although it may not be experienced often. It could be handled by keeping a collection of previously used refresh tokens to reference - and maybe crossing referencing other info like IP addresses or similar. Just brainstorming here. If you put together a solution, please return and post your Github link. Good thoughts and discussion!
JWT Authentication | Node JS and Express tutorials for Beginners
1:00:03
Difference between cookies, session and tokens
11:53
Valentin Despa
Рет қаралды 603 М.
Double Stacked Pizza @Lionfield @ChefRush
00:33
albert_cancook
Рет қаралды 60 МЛН
Scary Teacher 3D Nick Troll Squid Game in Brush Teeth White or Black Challenge #shorts
00:47
The Story of Next.js
12:13
uidotdev
Рет қаралды 555 М.
Node.js File Upload API with Express Tutorial
35:25
Dave Gray
Рет қаралды 65 М.
NextJS Parallel Routes Explained with a Simple Example
14:04
Dave Gray
Рет қаралды 9 М.
tRPC, gRPC, GraphQL or REST: when to use what?
10:46
Software Developer Diaries
Рет қаралды 74 М.
GraphQL vs REST: Which is Better for APIs?
7:31
IBM Technology
Рет қаралды 190 М.
Building HTTP Server in NodeJS
17:56
Piyush Garg
Рет қаралды 95 М.
Build an API Proxy Server - Hide Your API Keys, Rate Limiting & Caching
32:20