No video

React Persistent User Login Authentication with JWT Tokens

  Рет қаралды 192,223

Dave Gray

Dave Gray

Күн бұрын

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGra...
Learn how to add persistent user login authentication with JWT tokens to your React app. We will not store JWT tokens in local storage or session storage. That's not secure! The user login will persist when the React app is refreshed, reloaded, or revisited unless the user logs out or the refresh token has expired.
💖 Support me on Patreon ➜ / davegray
⭐ Become a full-stack web dev with Zero To Mastery Courses:
- Advanced React: bit.ly/AdvReac...
- Jr to Senior Web Dev Roadmap: bit.ly/WebDevR...
- Master FAANG Coding Interviews: bit.ly/FAANGIn...
🚩 Subscribe ➜ bit.ly/3nGHmNn
🚀 React JS for Beginners full course - 9 hours: • React JS Full Course f...
👀 React Login tutorial series playlist: • React Login, Registrat...
🔗 Starter Source Code: github.com/git...
🔗 Completed Source Code: github.com/git...
❗ NOTE: Two updates in source code AFTER video tutorial completed:
1) Added persist to useEffect in PersistLogin component to prevent unwanted call to verifyRefreshToken.
2) RequireAuth component now checks auth.accessToken instead of auth.user to support the persistent login. If you want to leave this as auth.user, just retrieve the user again inside the useRefreshToken hook.
📬 Course Updates ➜ courses.davegr...
React Persistent User Login Authentication with JWT Tokens
(00:00) Intro
(00:45) Welcome Discussion
(01:22) Current state of the app
(03:02) Why want a persistent login?
(04:05) PersistLogin component
(10:52) useRefreshToken update
(12:39) Add PersistLogin to App
(14:34) Test the Persistent Login
(16:07) Security Issue #1
(16:42) useLogout hook
(19:47) Add logout to Home
(21:35) Test with no refresh cookie
(22:44) Test with a refresh token
(23:34) Test with an expired refresh token
(26:04) Security Issue #2
(27:13) Adding new state to AuthProvider
(28:54) PersistLogin update
(30:18) Login update
(33:41) Test Trust Device toggle
(35:10) Fix a memory leak
☕ Buy Me A Coffee: www.buymeacoff...
The React Login Authentication Series:
1) React Register Form with Validation, Axios and a11y: • React JS Form Validati...
2) React User Login and Authentication with Axios: • React User Login and A...
3) React Protected Routes | Role-Based Authorization: • React Protected Routes...
4) React Login Authentication with JWT Access, Refresh Tokens, Cookies and Axios: • React Login Authentica...
5) This video!
🔗 Node JS Full Course (with source code) for building the backend REST API: • Node.js Full Course fo...
🔗 React Router Version 6 in 20 minutes: • React Router v6 in 20 ...
🔗 FontAwesome for React:
fontawesome.co...
🔗 RegExr for Regular Expressions: regexr.com/
📚 JWT References:
Intro to JSON Web Tokens: jwt.io/introdu...
All You Need to Know About Storing JWT in the Frontend: dev.to/cotter/...
Cross-Site Scripting (XSS): owasp.org/www-...
Cross-Site Request Forgery (CSRF): owasp.org/www-...
📚 Accessible Form References:
WebAIM.org - Advanced Forms: webaim.org/tec...
WebAIM.org - Form Validation: webaim.org/tec...
MDN - Aria Attributes:
aria-invalid: developer.mozi...
aria-describedby: developer.mozi...
aria-live: developer.mozi...
aria-label: developer.mozi...
🔗 ES7 React JS Snippets Extension for VS Code:
marketplace.vi...
🔗 React Dev Tools Extension for Chrome:
chrome.google....
📚 References:
ReactJS Official site: reactjs.org/
React Wikipedia: en.wikipedia.o...)
React Jobs: www.ziprecruit...
✅ Follow Me:
Github: github.com/git...
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this tutorial about Persistent User Login Authentication with JWT Tokens in React helpful? If so, please share. Let me know your thoughts in the comments.
#react #login #persistent

Пікірлер: 491
@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: kzfaq.info/sun/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@miguel5088
@miguel5088 Ай бұрын
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 KZfaq. 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! 💯
@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! 🙏💯
@dpuerto
@dpuerto 10 ай бұрын
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!
@D4arkl0rd
@D4arkl0rd Жыл бұрын
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! 🚀🚀
@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! 💯🙏
@roberaabera9222
@roberaabera9222 4 ай бұрын
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! 🙏🙏
@makarikevin
@makarikevin 10 ай бұрын
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 !
@sundayucheawaji6206
@sundayucheawaji6206 2 ай бұрын
Thank God I came across this channel. I really learnt a lot. Thank you very much, Dave. You are truly an inspiration to many.
@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!
@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!
@pavankulal9311
@pavankulal9311 4 ай бұрын
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 4 ай бұрын
Glad it was helpful!
@mikutaa
@mikutaa 5 ай бұрын
This is the best explanation of the authentication mechanism I've ever seen. Thanks!🙏
@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.
@Lykkos29
@Lykkos29 5 ай бұрын
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 5 ай бұрын
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! 🙏🚀
@aqilbekabilaev5647
@aqilbekabilaev5647 2 жыл бұрын
I wish there was a feature in KZfaq 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! 💯🙌
@ChandujobsApplications
@ChandujobsApplications 5 ай бұрын
No udemy could teach this much high level content....... even stephen grider also could not give this much high level content...... thank you sir!
@angel11592
@angel11592 10 ай бұрын
Hi, I just wanted to say thank you a lot of this series. Really insightful and easy to follow along.
@r1shabhnegi
@r1shabhnegi 4 ай бұрын
this was an amazing lecture, I learned a lot from you Dave.
@ravenMK_
@ravenMK_ 2 жыл бұрын
Best Series out there! Thank you Dave. Loving your content
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 🙏
@nurettinsen473
@nurettinsen473 8 ай бұрын
"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 4 ай бұрын
Can be accessed in an xss attack
@heygarryification
@heygarryification Жыл бұрын
Hey Dave, this is one of the best tutorials I've ever watched. Thanks for the good job!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you for the kind words! 🙏
@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 ?
@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: kzfaq.info/get/bejne/bpeWlL2r1ZecfoE.html
@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 6 ай бұрын
Same here
@coolme7437
@coolme7437 6 ай бұрын
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 8 күн бұрын
@@coolme7437 late but also wondering the exact same thing. did you figure it out?
@coolme7437
@coolme7437 3 күн бұрын
@@danyeun01 ask GPT
@user-xc3vj5te5y
@user-xc3vj5te5y 8 ай бұрын
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 8 ай бұрын
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.
@user-qj1wu4jt3r
@user-qj1wu4jt3r 10 ай бұрын
Thank you for your tutorials
@DaveGrayTeachesCode
@DaveGrayTeachesCode 10 ай бұрын
Thank you for the support! 💯
@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: kzfaq.info/get/bejne/bpeWlL2r1ZecfoE.html ..as for the AbortController, I discuss in a few videos (like this one when I update the useAxios hook for React 18: kzfaq.info/get/bejne/hJphdcKEu8rep5s.html), but you can always reference MDN as their documentation is great: developer.mozilla.org/en-US/docs/Web/API/AbortController
@majkel1381
@majkel1381 8 ай бұрын
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
@harrymuthee9666
@harrymuthee9666 2 жыл бұрын
Building this project has been quite informative...Keep up with the quality content💯🔥🔥
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks! Will do! 🚀🚀
@danyeun01
@danyeun01 8 күн бұрын
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.
@anandca4096
@anandca4096 2 жыл бұрын
There're not much videos like this in utube ... Thanks ❤️ very helpful
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome!
@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?
@krantinebhwani8737
@krantinebhwani8737 Жыл бұрын
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 Жыл бұрын
I am currently using the Github theme for VS Code and I think I used it in this video, too.
@juanmamani2110
@juanmamani2110 4 ай бұрын
Best 37 minutes of the day! thanks for sharing.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 4 ай бұрын
Glad you enjoyed it!
@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.
@lukeharwood6985
@lukeharwood6985 Жыл бұрын
Thank you so much! Best JWT tutorials on KZfaq!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're very welcome!
@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 6 ай бұрын
I also got stuck at the same point. IDK how it worked in his system. I figured it out while watching the video.
@Ulasp
@Ulasp 4 ай бұрын
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
@hanif3661
@hanif3661 9 ай бұрын
Dave you are an amazing instructor. ✌️🎉
@brianmuteti6217
@brianmuteti6217 3 ай бұрын
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.
@shivaakrish
@shivaakrish 28 күн бұрын
@30:00 How is it skipping the verifyRefreshToken call when we add the !persist check ?
@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. 💯
@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 19 күн бұрын
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?
@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 Жыл бұрын
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)..
@hamidabdolrahimi4606
@hamidabdolrahimi4606 Жыл бұрын
Thank you man. Awesome, best tutorial ever. Keep it up
@emad_naeim
@emad_naeim Жыл бұрын
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
@coolme7437
@coolme7437 6 ай бұрын
I'm not getting how persist is working? Why !persist was not applied in the useeffect before checking !auth ?
@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. 🚀
@alext8593
@alext8593 Жыл бұрын
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 Жыл бұрын
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: kzfaq.info/sun/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: kzfaq.info/get/bejne/qZNknpiFyK2veJs.html ...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 Жыл бұрын
@@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 Жыл бұрын
did you found a solution for the first point? 😅
@MeAsMeButMe
@MeAsMeButMe Жыл бұрын
@@alext8593 I was searching for this question! The user better hope they remember to log out in such a case! xD
@alext8593
@alext8593 Жыл бұрын
@@MeAsMeButMe have a little message in the navbar saying "don't forget to logout" lmao
@wigglorboy
@wigglorboy Жыл бұрын
This is the only tutorial I have seen that does this properly. Truly great! Btw, how should I handle redirect when I’m logged in but go to the login-endpoint? I should be redirected in that case, right?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thanks! Answer: Not necessarily. NextAuth and others don't do this either. You can assume if your user goes to the login page, they want to login in with another account. If you want, you can check if they are logged in on the page and redirect.
@wigglorboy
@wigglorboy Жыл бұрын
@@DaveGrayTeachesCode Ah, I see! Can i do this by setting a value in localstorage when i log in and remove it when i log out?
@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. 💯
@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.
@MP-ni2qf
@MP-ni2qf Ай бұрын
Can you help me? When I setAuth(prev) is return nothing even though there is respone.data in it
@emilenascivet4787
@emilenascivet4787 Жыл бұрын
THANK GOD YOU EXIST
@soy-luisarrieta
@soy-luisarrieta 11 ай бұрын
Dave, my persistent user login is not working because my refresh token API requires a token to identify the user. PDD: Thank you so much for this playlist, it's amazing!!
@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.
@therevenant9296
@therevenant9296 4 ай бұрын
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?
@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. 🙂
@kirillzlobin7135
@kirillzlobin7135 5 ай бұрын
35:05 - Important error fix - Cannot Perform a React state update on an unmounted component
@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.
@draicor
@draicor Жыл бұрын
Hey Dave! Thanks for doing this intermediate react tutorials, they are so valuable! I have a question, on the Login component, on line 45, we set the Auth using setAuth and we store whats coming from the backend, the roles and the accessToken, but we also store the user and the password on the state of the app. This is not neccesary, right? since we are checking if there is an accessToken inside the auth.accessToken state, user is no longer needed, and the password either, correct? this was just for console logging purposes?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
As far as I remember, you are correct. There is no harm in storing a username in app state if you want, but I don't suggest that for a password. There are a few more videos in this series and one is where I suggest some best practices which addresses this in more detail.
@nishantmishra895
@nishantmishra895 7 ай бұрын
Thanks a Lot Dave.
@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!
@sanjaybhan1585
@sanjaybhan1585 2 жыл бұрын
This is simple and nice as usual 👌
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad to hear it! Thank you! 🙏🙏
@MinhLe-lc7tk
@MinhLe-lc7tk 2 жыл бұрын
Hi Dave, thanks for your great tutorial. Will there be also a tutorial for Persistent User Login Authentication with JWT Tokens but with Redux Tookit and RTK Query? It would be fun, i think.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks for the request! 💯
@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 💯
@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: kzfaq.info/get/bejne/pqeqpNaUqd6ZaGQ.html - this tutorial does not show the JWT implementation, but they do support it.
@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: kzfaq.info/sun/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@silali
@silali 2 жыл бұрын
Thanks for pointing that out@@DaveGrayTeachesCode
@jordanjordanov6801
@jordanjordanov6801 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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?
@fzkhan
@fzkhan 6 ай бұрын
you explain very nice.
@ggsgetafaf1167
@ggsgetafaf1167 2 ай бұрын
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
@dharmeshgohil9375
@dharmeshgohil9375 2 жыл бұрын
you have something different content loved it most keep doing awesome work
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Dharmesh! 🙏🙏
@sungjuyea4627
@sungjuyea4627 Жыл бұрын
Is there any way that I could workaround using localStorage?
@hemantjain2510
@hemantjain2510 2 жыл бұрын
Was waiting for this.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks Hemant! 💯
@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: kzfaq.info/get/bejne/qZNknpiFyK2veJs.html ..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 🙂
@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.
@georgefromohio
@georgefromohio Жыл бұрын
Great videos as usual Dave! Quick Q - Do you have suggestions on how to deal with storing JWTs in memory when users open multiple tabs? With the implementation shown in this video, opening a new tab will refresh the token and expire the token stored on the source tab?... Or is the less secure localStorage/secure cookie option the only way to handle a requirement like that?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You could use another auth strategy - say just use one access token stored in memory (state). Keep it stateless on the backend so only validating the token - no storage of the token for comparisons. You would need to login on each tab, but one would not interfere with the other. That's safer than localStorage.
@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.
@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).
@draco2716
@draco2716 2 жыл бұрын
Hi Dave, thank you for the tutorials, I've gone through both the NodeJS and and React authentication series, and I've learned alot! Was just wondering if you've also noticed the "flicker" that happens once you click the sign out button on the home page? You can see it @21:38 in the video, the route is set to /login and then it navigates to /linkpage, as it awaits the logout and then navigates. Would you be able to explain why we chose await logout()? Thanks again!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Great question. When we logout, the RequireAuth component wants to send us to the login screen immediately. However, we also have React Router navigate us to the homescreen in this example. I'm sure this could be adjusted for a smoother experience. Maybe set a state value that RequireAuth references instead of always defaulting to the login page. Just one idea.
@Mohammedkhaled-zf1wr
@Mohammedkhaled-zf1wr Жыл бұрын
@@DaveGrayTeachesCode but here dave, requireAuth component shouldn't have been rendered beacaue we are heading to public route (linkpage) not private route? am I missing something???
@dailycodingJs
@dailycodingJs Жыл бұрын
Thank you Dave , you are a legend
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@igmtink
@igmtink 4 ай бұрын
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
@andrewijaya2162
@andrewijaya2162 11 ай бұрын
Bro you're the best Greets from indonesia
@timelsaer6729
@timelsaer6729 2 жыл бұрын
This content was crazy, thank's a lot!!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome!
@nada125love
@nada125love Жыл бұрын
this is premium content
@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 ?
@DayyanAli200
@DayyanAli200 Жыл бұрын
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 Жыл бұрын
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.
@chrisstucker1813
@chrisstucker1813 10 ай бұрын
Hi dave great tutorial. At 2:44 i notice in the console that it displays xr.js and the local host stuff. But in my app it shows the actual code of the React client app which is obviously not good for security. How do you get it to display just the request rejection and not the react code? Ideally I dont want the client to see that there was an error in User.js or whatever as they can click on the error and see my react code. Thanks
@mateusbessadev
@mateusbessadev 7 ай бұрын
Thanks for these videos! 🙏🙏
@tupac0199
@tupac0199 2 жыл бұрын
best react youtube channel
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 🙏
@eitanshalev1
@eitanshalev1 2 жыл бұрын
Hi Dave, thank you so much for all your classes. It is really the best classes I found online. I followed your training on Persistent User Login Authentication. I'm using React 18 and I find out that if I'm replacing ReactDOM.render with root.render (as suggested in version 18) it is not working. I'm getting "Canceled Error" from the backend and getting back to the login. Will appreciate if you have any suggestion. Thanks in advance
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You must be using StrictMode. In React 18, strict mode renders twice. That means the component unmounts once and calls the useEffect clean up function which calls the abort controller to cancel a request.
@eitanshalev1
@eitanshalev1 2 жыл бұрын
@@DaveGrayTeachesCode Thank you so much, this was the issue.
@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.
@wasitjamal7392
@wasitjamal7392 6 ай бұрын
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 6 ай бұрын
The refresh token is stored in an httpOnly secure cookie - not in state.
Harley Quinn lost the Joker forever!!!#Harley Quinn #joker
00:19
Harley Quinn with the Joker
Рет қаралды 24 МЛН
Secret Experiment Toothpaste Pt.4 😱 #shorts
00:35
Mr DegrEE
Рет қаралды 42 МЛН
НЫСАНА КОНЦЕРТ 2024
2:26:34
Нысана театры
Рет қаралды 1,8 МЛН
IQ Level: 10000
00:10
Younes Zarou
Рет қаралды 13 МЛН
Harley Quinn lost the Joker forever!!!#Harley Quinn #joker
00:19
Harley Quinn with the Joker
Рет қаралды 24 МЛН