React Persistent User Login Authentication with JWT Tokens

  Рет қаралды 199,199

Dave Gray

Dave Gray

Күн бұрын

Пікірлер: 494
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
In this series of videos, we've been creating a full React registration and login authentication system. We've built registration and login forms, applied protected routes that respond to user roles, and implemented continuous JWT authentication. Now, we'll add login persistence to the app so a page refresh - or even navigating away and returning - will not logout an authenticated user who has a valid refresh token. This solution does not use localStorage or sessionStorage for JWT token storage. If you haven't, I recommend starting at the beginning of this auth series playlist: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@miguel5088
@miguel5088 4 ай бұрын
Please I am stuck
@victoronwe906
@victoronwe906 2 жыл бұрын
This is simply a top notch premium content. Maintain this path and soon you will be the biggest react channel on KZbin. To be honest most paid courses on udemy do not give as much value as you have. Thanks for your great job Dave.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Wow, thank you so much for the kind words! 💯 I'll keep going! 🚀
@siddiqahmed3274
@siddiqahmed3274 2 жыл бұрын
yes it is truly top notch. nobody I have come across is making such high quality tutorials. God bless you SIR. And thanks a million ❤
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@siddiqahmed3274 thank you!
@victoronwe906
@victoronwe906 2 жыл бұрын
@@siddiqahmed3274 Exactly, and this is the channel advantage
@victoronwe906
@victoronwe906 2 жыл бұрын
@@DaveGrayTeachesCode Excellent. Am really looking forward for you to build a project with production structure. Something with different layouts, loading state, state management, error handling etc. Any project that is well crafted for production will greatly be appreciated. Plus you can reach out to Traversy media and publish such project on his channel. I believe it will add atleast 10k subscribers to your channel.
@ebratz
@ebratz 2 жыл бұрын
This kind of intermediate/advanced tutorials are much appreciated. Keep the awesome job coming!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Eduardo! 💯
@dpuerto
@dpuerto Жыл бұрын
This is so much fun! I have been rewriting this for Azure CosmosDB NoSQL API and Azure Table and removing axios in lieu of fetch to remove dependencies. Next is to use TypeScript. I wish I started this tutorial by making it typeScript, but after this auth series I'll have a couple foundations to work with! Thanks for the backend! I am learning a lot about Node.js and I love it!
@mitpancholi8089
@mitpancholi8089 2 жыл бұрын
This tutorial has it all you need to create standard login flow, and I realized that this is how it should be done. In real situation security is often overlooked. Every bit of this video is precious with advanced material. Thanks for sharing 👍. I binge watched this series of tutorials 😂
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're very welcome! 🙏💯
@noone_and_nobody
@noone_and_nobody Жыл бұрын
Started the series sometime last evening and continuing this first thing early in the morning. Great work Dave! And thank you very much for this.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@kartikarora3521
@kartikarora3521 2 жыл бұрын
Thanks for this, now I can build entire login and signup using React and JWT for production.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Absolutely! I'll look forward to seeing what you create! 🚀🚀
@roberaabera9222
@roberaabera9222 7 ай бұрын
I feel like you are the only youtuber who post what I'm looking for my projects. Great Job👍👍👍!
@tosandeepyandra
@tosandeepyandra 2 жыл бұрын
i started learning REACT .. i have seen many videos, but i am not able to connect to any content ... but with your content .. i am very much connected .. YOU ARE REALLY GENIUS ... Thanks a lot .. looking forward for additional videos on react
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words, Sandeep! 🙏🙏
@sundayucheawaji6206
@sundayucheawaji6206 5 ай бұрын
Thank God I came across this channel. I really learnt a lot. Thank you very much, Dave. You are truly an inspiration to many.
@makarikevin
@makarikevin Жыл бұрын
This being your last edition to React Login Authentication Series, I have to put my comment here. I have used all of your 5 series to develop a full working React JS Admin Web application (deployed on Digital Ocean) with little-to-zero background in React JS. Since I used Spring Boot as the backend, access token refresh withCredentials=true (cookies) didn't work for me (as I have other custom headers, and an Android app consuming the same APIs) and therefore opted to go with storing the refresh token in the local storage. I know this is a huge security flaw by design but as of now it is working fine for me and I'm okay with it (as I explore a more secure way to do it). I must admit that your tutorials are so straightforward, simple to follow, relevant and so resourceful (to an extend that I have added them all to my playlist). All my credit therefore comes back to you, in retribution, for the wonderful work (I wish I could buy you coffee 😊) and will continue watching more of your videos, Sir !
@mikutaa
@mikutaa 8 ай бұрын
This is the best explanation of the authentication mechanism I've ever seen. Thanks!🙏
@timothyclarke16
@timothyclarke16 2 жыл бұрын
Thanks Dave, your videos are great! You're really the only one out there who addresses security to this level while going through tutorials.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome, Timothy! 💯🙏
@Jeff-bu2jm
@Jeff-bu2jm Жыл бұрын
Brother, I've been searching a long long time for tutorials like this. So many beginner tutorials but nothing intermediate - advanced. Thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're very welcome!
@pavankulal9311
@pavankulal9311 7 ай бұрын
thank you so much dave sir for this video🙏. I learned nodeJs recently and did not know how use access and refresh token . I used it for my todo app and because of ease of teaching i could debug errors easily and customised code according to me .
@DaveGrayTeachesCode
@DaveGrayTeachesCode 7 ай бұрын
Glad it was helpful!
@HarmanSingh-tp7xs
@HarmanSingh-tp7xs Жыл бұрын
Great Content Sir ! Best Playlist to understand JWT handling on Frontend. Recently finished your Nodejs Course, loved it !😇
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Awesome, thank you!
@r1shabhnegi
@r1shabhnegi 7 ай бұрын
this was an amazing lecture, I learned a lot from you Dave.
@aqilbekabilaev5647
@aqilbekabilaev5647 2 жыл бұрын
I wish there was a feature in KZbin to like videos more than once. I would click the like btn till the morning. Thanks sir! Your work are much more than premium content. I really wish the best for you! Keep it up!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words! 💯🙌
@Lykkos-321
@Lykkos-321 8 ай бұрын
amazing tutorial sir, so well explained that even the backend logic in some sections of this video that you're explaining is very clear that I'm applying to Spring Boot to make a logout and login functionality without the necessity of watching external tutorials for it! 10/10!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 8 ай бұрын
You are most welcome
@azhardev9641
@azhardev9641 2 жыл бұрын
OMG. You code on another level bro. I am not exaggerating, you have the finest tutoring method, among tutors all over yt. Just keep sharing. Thanks 🙏
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you so much 😀 I appreciate your kind words! 🙏🚀
@ChandujobsApplications
@ChandujobsApplications 8 ай бұрын
No udemy could teach this much high level content....... even stephen grider also could not give this much high level content...... thank you sir!
@mikejones8519
@mikejones8519 2 жыл бұрын
You are very clear and thorough in your explanations. Very much appreciate your content!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Mike! 💯
@jhanmateo9583
@jhanmateo9583 Жыл бұрын
I would recommend this playlist it's so informative. Well explained and the example code is clean.
@ravenMK_
@ravenMK_ 2 жыл бұрын
Best Series out there! Thank you Dave. Loving your content
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 🙏
@angel11592
@angel11592 Жыл бұрын
Hi, I just wanted to say thank you a lot of this series. Really insightful and easy to follow along.
@majkel1381
@majkel1381 11 ай бұрын
If You check to not trust the device, log in, then refresh page, then type manualy secured route that was viable for just logged out user, this will authorize him and grant new token, thus logging him in anyway
@heygarryification
@heygarryification 2 жыл бұрын
Hey Dave, this is one of the best tutorials I've ever watched. Thanks for the good job!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words! 🙏
@TanveerAhmed-b7s
@TanveerAhmed-b7s 11 ай бұрын
Hi Dave, great content. one question. In the previous tutorial you mentioned that we should store the access token in app state and refresh token in http only cookie. I cannot find where you have actually stored the refresh token on the frontend. all I get is that you call the /refresh endpoint without any token and you get back the new access token.
@Waasi_explores
@Waasi_explores 11 ай бұрын
The refreshToken was stored as an HTTP only secure cookie at the backend. In summary, the backend supplies it upon authentication(log in) but you can't see or access it in the frontend. You can check the source code of the node REST api used for this tut, it's right there.
@juanmamani2110
@juanmamani2110 7 ай бұрын
Best 37 minutes of the day! thanks for sharing.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 7 ай бұрын
Glad you enjoyed it!
@harrymuthee9666
@harrymuthee9666 2 жыл бұрын
Building this project has been quite informative...Keep up with the quality content💯🔥🔥
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks! Will do! 🚀🚀
@anandca4096
@anandca4096 2 жыл бұрын
There're not much videos like this in utube ... Thanks ❤️ very helpful
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome!
@pliniojr95
@pliniojr95 Жыл бұрын
I got a little confused about the logic used when we implemented the persist state in the PersistLogin component: !persist ? : isLoading ? Loading... :
@coolme7437
@coolme7437 9 ай бұрын
Same here
@coolme7437
@coolme7437 9 ай бұрын
I'm not getting how this is working, even if persist value true or false he is showing the The useEffect will still make the refresh() API call.
@danyeun01
@danyeun01 3 ай бұрын
@@coolme7437 late but also wondering the exact same thing. did you figure it out?
@coolme7437
@coolme7437 3 ай бұрын
@@danyeun01 ask GPT
@annastoyanova1722
@annastoyanova1722 Жыл бұрын
React 18 is mounting useEffect twice even with [], which is causing the axios calls to be canceled and called a second time.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
This only happens in development with strict mode. Discussion and fix here: kzbin.info/www/bejne/bmLJko2wpZZrhK8
@lukeharwood6985
@lukeharwood6985 2 жыл бұрын
Thank you so much! Best JWT tutorials on KZbin!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're very welcome!
@ЮрийНосов-щ8ц
@ЮрийНосов-щ8ц Жыл бұрын
Thank you for your tutorials
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you for the support! 💯
@kevl7129
@kevl7129 Жыл бұрын
Unless I've done it wrong, the persist/isLoading chained ternary check still results in the verifyRefreshToken function being called whether persist is true or false - so even though access is not granted to protected routes, a token is returned from the server and stored in state - and in my case, so is some user info. A bad actor could see this data in the request response if they used the console. I fixed this by (in my case) checking for the persist state in the useEffect instead so that if persist isn't 'true', the verification function isn't called at all.
@coolme7437
@coolme7437 9 ай бұрын
I also got stuck at the same point. IDK how it worked in his system. I figured it out while watching the video.
@codewithadi8279
@codewithadi8279 Жыл бұрын
29:28 Suppose I don't want to include isLoading in PersistLogin Component. Then the condition will be { !persist ? : } If the persist is true then show the Outlet, if persist is false then also show the Outlet, then how do we differentiate whether we trust the device or not. My humble request to you sir, Please explain this once.
@mostafaibrahem722
@mostafaibrahem722 Жыл бұрын
Did you figured out the idea ?
@thattablebloke
@thattablebloke 2 жыл бұрын
Note for anyonne getting an error like : Unhandled Rejection (SyntaxError): Unexpected token u in JSON at position 0 If you have this error you may not need to parse the JSON in the persist state of AuthProvider. So go from this.. const [persist, setPersist] = useState(JSON.parse(localStorage.getItem("persist")) || false); .. to this.. const [persist, setPersist] = useState(localStorage.getItem("persist") || false);
@ramziosta
@ramziosta 2 жыл бұрын
this worked for two tries then it stopped, is it still working for you?
@varshithgowdav9892
@varshithgowdav9892 2 ай бұрын
Hi Dave, How does adding simple check prevent user to reverify the useEffect in persistLogin runs regard less of how we are loading a component and there will be http only cookie that will help in persisting user the user.
@shivaakrish
@shivaakrish 3 ай бұрын
@30:00 How is it skipping the verifyRefreshToken call when we add the !persist check ?
@hanif3661
@hanif3661 Жыл бұрын
Dave you are an amazing instructor. ✌️🎉
@brianmuteti6217
@brianmuteti6217 6 ай бұрын
Hi Dave. Thank you for the amazing tutorial. It has helped me learn a lot. I was wondering if the same concept can be implemented when a user has multiple devices. This is because each login will update the refreshToken in the database and render existing login in a another device invalid.
@krantinebhwani8737
@krantinebhwani8737 2 жыл бұрын
Great tutorial, followed it from beginning to end it was basically flawless! Learnt a lot and your teaching style is easy to follow and very consistent. Thanks a lot for this you earned a subscriber. PS. is it possible to know which vscode theme you were using in this video? thanks!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I am currently using the Github theme for VS Code and I think I used it in this video, too.
@khangle5968
@khangle5968 2 жыл бұрын
Love the new video. By the way, do you plan to make tutorials on a MERN stack project in the future? I've completed your React and Nodejs courses and I'm looking forward to a complete project. 😆
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks! And yes, I do. That said, this login authentication series is truly a MERN stack project, too. We're using the Node JS backend that uses Node/Express/MongoDB and React on the frontend. 💯
@Ulasp
@Ulasp 7 ай бұрын
Hey thank you a lot for these videos, they are really helpful! I've been following the series adapting it to a project im working on with typescript, so far everything was working until now trying to do the persistent login authentication, it seems after refreshing the page, the auth data is lost and sends undefined forcing me go back to login page, even with the PersistLogin component and that, I would appreciate some help im stuck
@samiullahsheikh5015
@samiullahsheikh5015 2 жыл бұрын
Excellent work Dave. But I have a question in mind. Suppose, someone doesn't "check trust this device" and left the computer and still access token is not expire. In this senario, if someone else change the localStorage value to TRUE via application tab. Now the person will have the access and will remain loge in. Please, do correct me if I'm wrong.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Ideally, your user signs out or closes their browser in a public setting. Of course, you cannot guard against everything a user may do. At your suggestion if the user did not log out or close their browser, a hacker would need to know to go to the local storage setting, change a specific setting, and if successful, they may gain access for the short time before the access token expires which I recommend giving a span of no more than 15 minutes. Consider a banking website as a real world example, if I don't log out or close my browser when I leave the computer, access remains for a limited amount of time.
@samiullahsheikh5015
@samiullahsheikh5015 2 жыл бұрын
@@DaveGrayTeachesCode Thank you for the explanation. 🙂
@usmanshahid8529
@usmanshahid8529 2 жыл бұрын
A tip from me : if you are using react 18 version then it wont work because cookie disappear after refreshing the page ,and we go in the !foundUser loop in refreshtoken controller ...so to avoid this thing ,you should remove strict behaviour of react from index js file and then it will work fine ❤️❤️ i have solved it by doing that 😊😊
@yw3546
@yw3546 2 жыл бұрын
I ran into the exact same issue, using version 18.2, it works on local but failed production. Glad to see your comment! Any side effect if removed strict mode?
@yw3546
@yw3546 2 жыл бұрын
Actually, removing strict mode does not persist my cookies. It works on local but not on server. Any hints?
@usmanshahid8529
@usmanshahid8529 2 жыл бұрын
@@yw3546 maybe you are doing something wrong with your code ,😊
@usmanshahid8529
@usmanshahid8529 2 жыл бұрын
@@yw3546 its my first time to use this react version ,so i am still searching about that 😊 if you have found something about that then share it with me 😊❤️
@yw3546
@yw3546 2 жыл бұрын
@@usmanshahid8529 Actually I found the root cause. To use SameSite=none you have to set Secure to true. And to use Secure=true you have to send through https or localhost. My project so far is still using http, so it works locally but not on production. It is a very interesting finding. I posted it to a separate comment as well.
@teemofan7056
@teemofan7056 3 ай бұрын
so what if i first login with persistent unchecked, then i refresh (should see the login page) and only check the persistent box. next I simply refresh, will this automatically log me in?
@DanielAzubuine
@DanielAzubuine Жыл бұрын
Dave Thanks for the tutorial. When Using UseEffect to get data using the useAxiosPrivate and the abort Controller, it fetches the data, but returns error. Why is it like this? and why should i use a abort controller
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I'm guessing you are using React 18 and this tutorial was made with React 17. The why and how to fix is discussed here: kzbin.info/www/bejne/bmLJko2wpZZrhK8 ..as for the AbortController, I discuss in a few videos (like this one when I update the useAxios hook for React 18: kzbin.info/www/bejne/hGWUc5KJi8mtrck), but you can always reference MDN as their documentation is great: developer.mozilla.org/en-US/docs/Web/API/AbortController
@iang9675
@iang9675 2 жыл бұрын
Great job Dave! Question - does the refresh token / set-cookie header also persist on the front end on a page reload? If so, is that cookie then used to get the new access token? Since local storage is not used to store the user or access token and the app's memory is wiped, I'm unsure how the re-login works.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Hi Ian - I think you've got the idea. The cookie is all that remains when a refresh/reload clears the auth state. Same for navigating away and returning. When you return, if you have chosen to persist your login, the cookie is sent to the refresh endpoint. If the refresh token has not expired, a new access token is issued which allows continued use. You can send the data you want - maybe a username or roles - inside the access token or outside. Later in this series, I recommend inside.
@draicor
@draicor 2 жыл бұрын
Exactly mate, the httpOnly cookie persist on the browser until the client removes it from the browser or it expires (remember the backend defines a maxAge for the cookie)..
@justtheone8544
@justtheone8544 2 жыл бұрын
Hello Dave Gray, Thanks for an amazing video! I just had a question, after login will the cookie containing the refresh token be saved after refresh?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Until replaced. The token within could expire while the cookie is saved (and should be allowed to).
@GabrielMartinez-ez9ue
@GabrielMartinez-ez9ue 2 жыл бұрын
Excellent. I am trying to implement this series using Nextjs. Its not at easy as it seems.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, and I understand! I hope to work with Nextjs later this year. 🚀
@ggsgetafaf1167
@ggsgetafaf1167 5 ай бұрын
thank you very much for your video. I learn a lot from it. but I have one question: In Component PersistLogin: {!persist ? : isLoading ? Loading ... : } To be honest with you, I do not understand why *persist* is false --> go to login page? After debugging (ignore StrictMode), I see: - If persist is *true*, the component will render *2 time* (one for the initial and second after having new access_token). - If persist is *false*, the component only renders one time although useRefreshToken hook still is called and updates auth through setAuth
@AdityaDey424
@AdityaDey424 Жыл бұрын
If the persist is false then move to outlet and if persist is false and isLoading is true then show the or else again move to outlet. So my question is when the verifyRefreshToken () will execute? If verifyRefreshToken () execute while we use PersistLogin component, as the dependency is [], and if persist is false then verifyRefreshToken() will work or not?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
It has been awhile since I made this, but in general, verifyRefreshToken is called when axios intercepts a request where the auth token is denied.
@therevenant9296
@therevenant9296 7 ай бұрын
Great lecture as always! I have always benefitted from them. I was just thinking it might be possible to store both access and refresh token in the cookies rather than sending the access token as request. I ask this because I come from the redux toolkit auth tutorial and there if I use redux persist I would have use local storage or so. I really dont want to store anything on the local storage as I feel it is not so safe? Whats your take?
@anhminh5479
@anhminh5479 2 жыл бұрын
Hi Dave, your tutorial help me a lot but i have an issue, if user logged in my app and they type "login" in the url, its still back login page, i want check if user is logged then they type login in url its redirect to dashboard page, can you give me some solution
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Move on to the next tutorial in this series to better understand routing.
@dark-dew
@dark-dew 2 жыл бұрын
Hello, Dave. The tutorial is great. I have a question. While logging out, if user doesn't have internet connection or if the logout request to the server fails then the cookie won't be cleared but user will be taken to login page. Now, if user again goes to protected routes then he/she will get access even if he/she has logged out. Shouldn't we check if the logout request to the server was successful before redirecting the user to login page?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
That's a good idea! The temporary situation you describe will only be possible before the token within the cookie has expired, but it sounds like it is possible. 💯
@hemantjain2510
@hemantjain2510 2 жыл бұрын
Was waiting for this.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks Hemant! 💯
@emad_naeim
@emad_naeim 2 жыл бұрын
Thanks for you tutorials, I learnt a lot from you, I have one question and hope you would answer me: if someone logged in without toggling "trust this device", and let's say he closed the browser at any time or the tab, then if you visit the website and toggle the "trust this device" then hit reload, wouldn't that send the stored refresh token then re-auth the previous user? I'm using react with .NET as backend could you help me with recommendation for solving this problem? 😅 thanks again
@rexbec2697
@rexbec2697 2 жыл бұрын
Hello Dave, I was wondering if you could just make a short video on how we can use Persistent login on NextJS.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the request 💯
@coolme7437
@coolme7437 9 ай бұрын
I'm not getting how persist is working? Why !persist was not applied in the useeffect before checking !auth ?
@MP-ni2qf
@MP-ni2qf 4 ай бұрын
Can you help me? When I setAuth(prev) is return nothing even though there is respone.data in it
@hamidabdolrahimi4606
@hamidabdolrahimi4606 Жыл бұрын
Thank you man. Awesome, best tutorial ever. Keep it up
@pallavkumarpatra1767
@pallavkumarpatra1767 Жыл бұрын
Hey dave, Its working perfectly with the localhost backend endpoint, but the cookies somehow doesnt work with a EC2 hosted backend endpoint.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Possibly http on localhost vs https when deployed. secure: true in the cookie for https.
@Ikhsannhuda.
@Ikhsannhuda. Жыл бұрын
Dave, this is superb! If you don't mind, using typescript might be more fun. 🤟
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Currently using TS in my Next.js series. Full TS course on my channel, too.
@onelook1870
@onelook1870 2 жыл бұрын
Awesome series of tutorials. Can you implement logging in multiple devices.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
That's a good request! It would require more changes to the backend node.js code to put in place.
@onelook1870
@onelook1870 2 жыл бұрын
@@DaveGrayTeachesCode Thanks for considering the request. It will be good tut for extending the feature.
@wasitjamal7392
@wasitjamal7392 9 ай бұрын
I have a question. At 14:34, when testing you press refresh but how does it send a refresh token in request if the auth state is lost in refresh?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 9 ай бұрын
The refresh token is stored in an httpOnly secure cookie - not in state.
@jordanjordanov6801
@jordanjordanov6801 2 жыл бұрын
Hi Dave I noticed that when refresh the page with trust this device set to false our session cookie is still in the browser (even if we are redirected to the login page) and if we set persist to true manually via chrome dev tools we can still continue our session isn't this a big security concern?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You can create a logout route that will delete the cookie. Otherwise, it will expire at the given time. Other measures can be taken - maybe try to clear browser history on logout or when a browser or tab is closed. There are lots of what-ifs here like what if a user walks away from the browser and doesn't log out? You are left with the expiration only. It is difficult to babysit every instance. If there is a huge security concern, my suggestion is to explain to the boss this feature can hurt the security of your app. Nothing in the frontend is 100% secure.
@CoinCoin86
@CoinCoin86 2 жыл бұрын
I'm also concerned about this issue. If you have a refresh token that last a longer time and can be used in a public area, you can put manually to true and reuse. How about trying to logout if you are accessing to the app with persist = false and having a refresh token? It may add latency if persist is false and not having an access token but add better security maybe?
@xDiggie
@xDiggie Жыл бұрын
Very helpful! Just wanna ask though, how would we prevent an authenticated user from accessing some of the public routes like login page or sign up page when manually typing in the URL or using the browser's navigation for those routes? Thanks!
@tupac0199
@tupac0199 2 жыл бұрын
best react youtube channel
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 🙏
@abdalrahmansuboh2695
@abdalrahmansuboh2695 2 жыл бұрын
Thank you DAve for this series but I have a question if the user is logged in how I can prevent them from accessing the login or register page ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Check the auth state. If it exists, useNavigate from React Router to redirect.
@waltergermanes4528
@waltergermanes4528 9 ай бұрын
Can you help me sir, when i add another route in front-end to display users in another page, it returns 401 in backend, I can't receive access token in auth header in verifyJWT, only the homepage can fetch the data and working, thanks in advance 🙏
@andysimmons8730
@andysimmons8730 Жыл бұрын
Hi Dave, I'm curios where did you learn all this? Not just this video but how are you able to go so in depth on all of these videos? Do you genuinely learn everything from the docs?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Reviewing docs is an important step. But I also read other articles daily, look at what others are doing, etc. Just take in all the information you can about a topic.
@autobot021
@autobot021 2 жыл бұрын
I still dont understand how the persist works ... where does it get the accessToken information when the page is refreshed ????
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I think you would understand better by understanding how the backend REST API works. You can learn how to build it here: kzbin.info/www/bejne/nGOoonh5nrl1gpo
@DwaparaTech
@DwaparaTech 2 жыл бұрын
Hi Dave my RequireiAuth is not waiting for the Persistent login to complete is component is redirected to login while auth is still stil waiting for data
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You might compare your code to my source code linked to in the description. Another consideration is React 18 strict mode which will mount and unmount each component before remounting. Remove it from your index.js for a quick fix. For a better fix, I have this video: kzbin.info/www/bejne/bmLJko2wpZZrhK8
@kaushikravikumar7472
@kaushikravikumar7472 Жыл бұрын
Excellent video Dave! Can you please let me know how you would handle the cookies in incognito mode? As I understand cookies won’t be sent by the browser if the front end and backend are from different domains.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
It won't work in Incognito because as you note, cookies are not an option.
@matianyu1
@matianyu1 2 жыл бұрын
great video, is cookie/session auth dead nowadays? can hardly find any quality videos explaining cookie/session. instead 99% are JWTs...
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I wouldn't say dead, but JWT is a popular choice - especially for use with REST APIs.
@sayedalisinasadat2908
@sayedalisinasadat2908 Жыл бұрын
Thanks for your sharing a nice video , if we use Spring Boot API what should we do ? if i can use this please tall me ?
@dailycodingJs
@dailycodingJs Жыл бұрын
Thank you Dave , you are a legend
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@sungjuyea4627
@sungjuyea4627 Жыл бұрын
Is there any way that I could workaround using localStorage?
@dragos.cojocaru
@dragos.cojocaru 2 жыл бұрын
I wouldn't recommend using this logic everywhere. If, for example, someone is using login into their account using a public computer without checking the persist, and just close the browser after they finished their work, another person can come and set persist to true in the local storage and just refresh the page and they will be logged in into the other user account. Is there a fix for this? 🧐
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Let's break this down... 1) I don't recommend using this everywhere either. In fact, I state in the video that you are more secure without it, but your boss or whoever may really want this functionality. And nothing is 100% secure in the frontend. 2) In the hypothetical situation you describe, a user has logged in, received a refresh token that has not yet expired, and walked away - possibly closed the browser - but did not log out. The log out process should delete the cookie. Now someone needs to use the computer, go to the browser history or otherwise pull up the same site, gets kicked to login page because they aren't logged in, check the persist checkbox (no need to manually edit localStorage - the checkbox will do it), and refresh the page. Yes, if they know to do all of that along with an existing refresh token that has not expired and a user that did not log out, they should gain access. 3) *What can be done?* I recommend JWT Rotation so the refresh token only last minutes instead of a day or days. My video on that is here: kzbin.info/www/bejne/qV6XnGiKmKx-fsk ..In addition, employee training and strongly suggesting not to use publicly available computers for this stuff since your boss insisted on this feature. 😃 It's a lot like email in that training is essential and can still be easily ignored allowing hacks to take place.
@dragos.cojocaru
@dragos.cojocaru 2 жыл бұрын
@@DaveGrayTeachesCode Thanks for guiding me 🙂
@kirillzlobin7135
@kirillzlobin7135 7 ай бұрын
Dave, please, please, please. I need help... For example, when we reloaded the page - we lost all data. The only thing we have - is just a refresh token. So, we will use this refresh token to get a new access token from /refresh endpoint. But how do we get the information about the user? Now we have only token. But if we want to show some user info? Like email and profile photo. Isn't this information is also sent when we log in and kept in memory? So our refresh endpoint should also send this, correct? Otherwise we should keep user's info in a localstorage
@DaveGrayTeachesCode
@DaveGrayTeachesCode 7 ай бұрын
The new access token lets you access the other information you need. Do not store any sensitive user data in localStorage. It is not secure.
@silali
@silali 2 жыл бұрын
This is very concise and informative, although I'm wondering where one stores the refresh token.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
This video is part of a series. The video before this discusses the refresh token in detail. It is stored in an httpOnly secure cookie. Full playlist: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@silali
@silali 2 жыл бұрын
Thanks for pointing that out@@DaveGrayTeachesCode
@danyeun01
@danyeun01 3 ай бұрын
if anyone else if having issues because of react 18 strictmode, you can use a useRef to ensure the useEffect in PersistLogin only runs once. otherwise, im not sure what other solution would be viable.
@bfmcoding4485
@bfmcoding4485 2 жыл бұрын
hi Dave, how if we have 3 login method in our app, login with username and password, login with google, and login with facebook. Is the jwt access and refresh token still needed in the other 2 login method (google and facebook) ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You do want to stay consistent. If including social logins, look into a solution like this that supports social logins and JWTs: kzbin.info/www/bejne/pnLdoqaZed1obpI - this tutorial does not show the JWT implementation, but they do support it.
@jefryhsinaga
@jefryhsinaga Жыл бұрын
hello, im newbie and have a question, is this works if backend and frontend at different server ?
@nurettinsen473
@nurettinsen473 11 ай бұрын
"Why do you think we should store access tokens in React context as memory instead of sessionStorage? Can you explain why not store them in sessionStorage?"
@kashishfatima581
@kashishfatima581 7 ай бұрын
Can be accessed in an xss attack
@cerritosrules
@cerritosrules Жыл бұрын
What exactly does the auth and setAuth state do in the AuthContext? I am trying to do this in typescript but the compiler keeps yelling at me saying the setAuth does not exist in the refreshToken hook. ):
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
If I remember correctly, there is a custom useAuth hook that has the auth state. That is what auth and setAuth represent.
@cerritosrules
@cerritosrules Жыл бұрын
@@DaveGrayTeachesCode so it just keeps track if the currently logged in user is authenticated? Like a true or false?
@teologomedio
@teologomedio 10 ай бұрын
Thanks for these videos! 🙏🙏
@robbertdoon7043
@robbertdoon7043 2 жыл бұрын
David, thank you for your great in depth tutorial. I sure could pick up a lot of things for my project so many kudos to you! I do have one question though and I really hope you can find the time to react (no pun intended, but haha!). When I refresh the page (the browser, like with the f5 key), the auth object (state) will become empty, and filled with roles and the token. In the useRefreshToken hook, you make use of ...prev in the return, but when I console.log prev, it's an empty object (after browser refresh), and therefore not restoring my set username. I can fix it by passing user in the refreshTokenController, but I really would like to make use of ...prev. Did I miss something (I do think I've looked everywhere) or can you (or any user in here!) help me out how to make it work without saving the state to local storage? Many thanks and keep up the great work! You mean a lot to us edit: eventually I want to only use ...prev and accessToken, as ...prev should already have the username and the roles in it and only overwrite the accessToken. I hope you understand what I'm after :-)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Good questions! You will always lose app state when you refresh or when you navigate away from the app and return. Anything you want to persist needs to come from the server. You can send it all inside the access token and decode the token when you receive it. Keep going to the "best practices" tutorial in this series for recommendations on that.
@KPBhan
@KPBhan 2 жыл бұрын
This is simple and nice as usual 👌
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad to hear it! Thank you! 🙏🙏
@fzkhan
@fzkhan 9 ай бұрын
you explain very nice.
@igmtink
@igmtink 7 ай бұрын
sir how about if the route is containing only user info and that user info is coming from the "{ auth } = useAuth" then the refresh token has expired when we visit the route that containing only user info it will not trigger the "verifyRefreshToken" because the user info is only coming from the "state"? like profile page that needs only user information so we can get that from "{ auth }" state right? so example the refresh token has expired and we visit the "profile" page it will not trigger the "verifyRefreshToken" as long as we don't refresh the browser or visit the another page that will triggering the inceptors
@DayyanAli200
@DayyanAli200 2 жыл бұрын
Hey Dave! Amazing series. I'm just confused as to what the isLoading does in the PersistLogin component. Can you elaborate a bit on that part here ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
isLoading is state that says the app is still loading data. You usually look at isLoading or similar states to show a spinner or loading message while the app retrieves what it needs.
@dharmeshgohil9375
@dharmeshgohil9375 2 жыл бұрын
you have something different content loved it most keep doing awesome work
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Dharmesh! 🙏🙏
@alext8593
@alext8593 2 жыл бұрын
Hi Dave. Nice video, but two questions!: 1) If the user doesn't toggle `persist` to `true` and logs in, they still receive a persistent refresh cookie. As such if they logout, then toggle `persist` to `true` and refresh the page, since the refresh cookie still exists in the browser, won't the the user get logged in again? If so, how can we prevent this? 2) Since refresh tokens are being recorded in mongoDB, if an authenticated user hits the `/logout` endpoint (but their refresh cookie has expired and therefore wasn't sent along with the request), how can we remove this expired token from the database? Thanks in advance, and keep up the good work! :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks Alex! 🙏 1) It would be a good idea to send a logout request with the logout action that will ask the server to "clear" (aka delete) the cookie. You can see an example of this in my current MERN Stack Project series: kzbin.info/aero/PL0Zuz27SZ-6P4dQUsoDatjEGpmBpcOW8V 2) This is a good discussion and something I have discussed in the comments for my Node.js JWT Rotation and Re-use Detection video here: kzbin.info/www/bejne/qV6XnGiKmKx-fsk ...it would also be a good idea to have a maintenance routine / function that eventually removed old tokens from the data. Often JWTs are used in a stateless manner - not stored in a db at all - but with re-use detection, you have to keep track of the old ones.
@alext8593
@alext8593 2 жыл бұрын
@@DaveGrayTeachesCode ​ Hi Dave, thanks for answering! I will check out the re-use detection video :) With respect to point 1), while I understand the use of `res.clearCookie` on '/logout', I'm specifically talking about refreshing the page while logged in (with `persist` === `false`), getting kicked back out, then toggling to `true` and refreshing the page and getting automatically logged back in again. I think this is happening because the a page refresh does not clear the site cookies, namely the refresh JWT. This is what's happening for me haha! If this isn't what happens in your app, no worries, I'll rewatch again :) Thanks!
@emad_naeim
@emad_naeim 2 жыл бұрын
did you found a solution for the first point? 😅
@Behold-the-Florist
@Behold-the-Florist Жыл бұрын
@@alext8593 I was searching for this question! The user better hope they remember to log out in such a case! xD
@alext8593
@alext8593 Жыл бұрын
@@Behold-the-Florist have a little message in the navbar saying "don't forget to logout" lmao
@chiragmehta2955
@chiragmehta2955 Жыл бұрын
hello dev, is accesstoken stored in memory, if so is it secure to xss attacks! please reply😅
@devproject8649
@devproject8649 Жыл бұрын
Hi Dave, I love your videos. I have a problem, my useEffect is executed twice because of react's strict mode, so my fetch to update the token is executed twice simultaneously which causes the second call to try to delete the cookie that the first one already deleted and this ends up generating an error.
@glry2dagrind
@glry2dagrind Жыл бұрын
Same. Did you figure this out?
@joshkny
@joshkny 2 жыл бұрын
Hi Dave, I had a question about the behavior of the trust device toggle: after logging out, when it is toggled on, I can still navigate to the protected routes. Is this a bug or a feature? If a bug, how can I adjust the behavior so the routes are still protected regardless of if the toggle is on or off. Thanks so much for this content. It's really helped me transition from LAMP to MERN!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Great question, Joshua! I did leave this a little open-ended here. You can have your logout function delete the persist flag in localStorage OR if tracking the refresh token on the server, the logout function could issue a request to delete the token on the server. Not all JWT auth setups track tokens in a database though. If using refresh token re-use detection, they do. I have a separate tutorial on that.
@AidinBehnood
@AidinBehnood Жыл бұрын
hi thank you for time and teaching. Do you have github for downloading the code ?
@AidinBehnood
@AidinBehnood Жыл бұрын
i found it thank you
这是自救的好办法 #路飞#海贼王
00:43
路飞与唐舞桐
Рет қаралды 126 МЛН
2 MAGIC SECRETS @denismagicshow @roman_magic
00:32
MasomkaMagic
Рет қаралды 34 МЛН
What Is JWT and Why Should You Use JWT
14:53
Web Dev Simplified
Рет қаралды 1,2 МЛН
Are we going back to PHP with fullstack JavaScript?
9:57
Maximilian Schwarzmüller
Рет қаралды 151 М.
JWT Authentication Tutorial - Node.js
27:36
Web Dev Simplified
Рет қаралды 1 МЛН
React Login Input Hooks for User Form Data
24:02
Dave Gray
Рет қаралды 37 М.
10 React Hooks Explained // Plus Build your own from Scratch
13:15
Fireship
Рет қаралды 1,4 МЛН