Тёмный

React Persistent User Login Authentication with JWT Tokens 

Dave Gray
Подписаться 321 тыс.
Просмотров 189 тыс.
50% 1

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
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/AdvReactDev
- Jr to Senior Web Dev Roadmap: bit.ly/WebDevRoadmap-JrtoSr
- Master FAANG Coding Interviews: bit.ly/FAANGInterview
🚩 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/gitdagray/react_jw...
🔗 Completed Source Code: github.com/gitdagray/react_pe...
❗ 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.davegray.codes/
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.buymeacoffee.com/davegray
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.com/v5.15/how-to-...
🔗 RegExr for Regular Expressions: regexr.com/
📚 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...
Cross-Site Scripting (XSS): owasp.org/www-community/attac...
Cross-Site Request Forgery (CSRF): owasp.org/www-community/attac...
📚 Accessible Form References:
WebAIM.org - Advanced Forms: webaim.org/techniques/forms/a...
WebAIM.org - Form Validation: webaim.org/techniques/formval...
MDN - Aria Attributes:
aria-invalid: developer.mozilla.org/en-US/d...
aria-describedby: developer.mozilla.org/en-US/d...
aria-live: developer.mozilla.org/en-US/d...
aria-label: developer.mozilla.org/en-US/d...
🔗 ES7 React JS Snippets Extension for VS Code:
marketplace.visualstudio.com/...
🔗 React Dev Tools Extension for Chrome:
chrome.google.com/webstore/de...
📚 References:
ReactJS Official site: reactjs.org/
React Wikipedia: en.wikipedia.org/wiki/React_(...)
React Jobs: www.ziprecruiter.com/candidat...
✅ Follow Me:
Github: github.com/gitdagray
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

Опубликовано:

 

14 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 486   
@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: ru-vid.com/group/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@miguel5088
@miguel5088 20 дней назад
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 RU-vid. 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! 💯
@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! 💯🙏
@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!
@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! 🙏💯
@angel11592
@angel11592 9 месяцев назад
Hi, I just wanted to say thank you a lot of this series. Really insightful and easy to follow along.
@dpuerto
@dpuerto 9 месяцев назад
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!
@jhanmateo9583
@jhanmateo9583 11 месяцев назад
I would recommend this playlist it's so informative. Well explained and the example code is clean.
@roberaabera9222
@roberaabera9222 3 месяца назад
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! 🙏🙏
@mikejones8519
@mikejones8519 2 года назад
You are very clear and thorough in your explanations. Very much appreciate your content!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you, Mike! 💯
@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! 🙏
@mikutaa
@mikutaa 4 месяца назад
This is the best explanation of the authentication mechanism I've ever seen. Thanks!🙏
@ravenMK_
@ravenMK_ 2 года назад
Best Series out there! Thank you Dave. Loving your content
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you! 🙏
@sundayucheawaji6206
@sundayucheawaji6206 Месяц назад
Thank God I came across this channel. I really learnt a lot. Thank you very much, Dave. You are truly an inspiration to many.
@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 3 месяца назад
this was an amazing lecture, I learned a lot from you Dave.
@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! 🚀🚀
@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! 🙏🚀
@anandca4096
@anandca4096 2 года назад
There're not much videos like this in utube ... Thanks ❤️ very helpful
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome!
@pavankulal9311
@pavankulal9311 2 месяца назад
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 2 месяца назад
Glad it was helpful!
@makarikevin
@makarikevin 9 месяцев назад
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 !
@lukeharwood6985
@lukeharwood6985 Год назад
Thank you so much! Best JWT tutorials on RU-vid!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're very welcome!
@harrymuthee9666
@harrymuthee9666 2 года назад
Building this project has been quite informative...Keep up with the quality content💯🔥🔥
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thanks! Will do! 🚀🚀
@hamidabdolrahimi4606
@hamidabdolrahimi4606 Год назад
Thank you man. Awesome, best tutorial ever. Keep it up
@aqilbekabilaev5647
@aqilbekabilaev5647 Год назад
I wish there was a feature in RU-vid 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 Год назад
Thank you for the kind words! 💯🙌
@Lykkos29
@Lykkos29 4 месяца назад
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 4 месяца назад
You are most welcome
@juanmamani2110
@juanmamani2110 3 месяца назад
Best 37 minutes of the day! thanks for sharing.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 3 месяца назад
Glad you enjoyed it!
@hanif3661
@hanif3661 8 месяцев назад
Dave you are an amazing instructor. ✌️🎉
@user-qj1wu4jt3r
@user-qj1wu4jt3r 9 месяцев назад
Thank you for your tutorials
@DaveGrayTeachesCode
@DaveGrayTeachesCode 9 месяцев назад
Thank you for the support! 💯
@sanjaybhan1585
@sanjaybhan1585 2 года назад
This is simple and nice as usual 👌
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Glad to hear it! Thank you! 🙏🙏
@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. 💯
@nishantmishra895
@nishantmishra895 6 месяцев назад
Thanks a Lot Dave.
@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.
@hemantjain2510
@hemantjain2510 2 года назад
Was waiting for this.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thanks Hemant! 💯
@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!
@fzkhan
@fzkhan 5 месяцев назад
you explain very nice.
@timelsaer6729
@timelsaer6729 2 года назад
This content was crazy, thank's a lot!!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome!
@dharmeshgohil9375
@dharmeshgohil9375 2 года назад
you have something different content loved it most keep doing awesome work
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you, Dharmesh! 🙏🙏
@mateusbessadev
@mateusbessadev 6 месяцев назад
Thanks for these videos! 🙏🙏
@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. 🚀
@muhammedcansoy6131
@muhammedcansoy6131 7 месяцев назад
excellent thank you !
@ChandujobsApplications
@ChandujobsApplications 4 месяца назад
No udemy could teach this much high level content....... even stephen grider also could not give this much high level content...... thank you sir!
@dailycodingJs
@dailycodingJs Год назад
Thank you Dave , you are a legend
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome!
@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.
@marcosfitzsimons
@marcosfitzsimons 10 месяцев назад
Thank you so much sr.
@surajregmi9965
@surajregmi9965 2 года назад
Huge Respect, Sir!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you, Suraj! 🙏
@kirillzlobin7135
@kirillzlobin7135 4 месяца назад
Amazing tutorials
@z-wingff6368
@z-wingff6368 4 месяца назад
Hey ! I want to practice this jwt authentication but how I can setup backend please help
@emilenascivet4787
@emilenascivet4787 Год назад
THANK GOD YOU EXIST
@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?
@andrewijaya2162
@andrewijaya2162 10 месяцев назад
Bro you're the best Greets from indonesia
@tupac0199
@tupac0199 2 года назад
best react youtube channel
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you! 🙏
@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.
@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.
@raiyanthedeveloper
@raiyanthedeveloper Год назад
top notch premium content
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you!
@jonathanlemos2690
@jonathanlemos2690 2 года назад
Hi Dave, hope you're well, for along time i was so confused on how JWT tokens works in authentication, and then, Thanks to your tutorials, I was able to understand it all, however i was trying to do some more complex things with the JWT tokens by implementing them or integrating them in React Authentications using Passport and its passport-jwt package, Can You please make a complete tutorial about "how to create a complete React Authentication (Login/Register) using JWT, Axios, Passport, Passport-jwt and Express Express-session". It would be fantástic, Thanks.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you, Jonathan! 🙏 That's a great request for a future tutorial 💯🚀
@profeskills768
@profeskills768 2 года назад
Thank you so mush!!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome! 💯
@majkel1381
@majkel1381 7 месяцев назад
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
@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: ru-vid.com/group/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@silali
@silali 2 года назад
Thanks for pointing that out@@DaveGrayTeachesCode
@brianmuteti6217
@brianmuteti6217 2 месяца назад
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.
@mohamedyoussef8835
@mohamedyoussef8835 2 года назад
Awesome Tutorial +++++++++++++++++++++ Thank You
@victorsunday3677
@victorsunday3677 2 года назад
Love this tutorial
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you! 🙏
@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.
@okayoh97
@okayoh97 2 года назад
Thank you, big thanks for this as I consider being able to complete a login authentication system a huge milestone! Following up on my comment on another video, is there a use case for anchor or Link tags? or does it not matter which I use?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
With React Router, you use Link tags and the "to" attribute. I hope this helps 🚀
@jor4288
@jor4288 2 года назад
So help! => Dave for president!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome! 🙏 Thanks for the nomination 😆
@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.
@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???
@therevenant9296
@therevenant9296 3 месяца назад
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?
@user-xc3vj5te5y
@user-xc3vj5te5y 7 месяцев назад
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 7 месяцев назад
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.
@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! 💯
@iang9675
@iang9675 Год назад
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 Год назад
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)..
@pliniojr95
@pliniojr95 11 месяцев назад
I got a little confused about the logic used when we implemented the persist state in the PersistLogin component: !persist ? : isLoading ? Loading... :
@coolme7437
@coolme7437 5 месяцев назад
Same here
@coolme7437
@coolme7437 5 месяцев назад
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.
@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: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-81faZzp18NM.html
@luisarrieta1501
@luisarrieta1501 10 месяцев назад
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!!
@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).
@Ulasp
@Ulasp 3 месяца назад
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
@nada125love
@nada125love 11 месяцев назад
this is premium content
@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!
@samieid443
@samieid443 Год назад
Thanks!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you for the support, Sami! 🙏💯
@Ca3yMiX
@Ca3yMiX 2 года назад
Hello Dave, Thanks for the react serie, can i have some suggestions about secure ways to persist data .. thanks
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
This tutorial shows a secure way to persist data. Look at the reference links in the video description, too. You will want to learn about secure httpOnly cookies.
@chrisstucker1813
@chrisstucker1813 9 месяцев назад
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
@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.
@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 💯
@jesusmendoza7774
@jesusmendoza7774 2 года назад
hey Dave, thanks for the awesome tutorial. One quick question, I've been trying to undertand how are validating if we are authenticated or not in our /refresh endpoint, are we sending the previous token somewhere? or how are we validating that?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
We're sending the refresh token that the client currently has. If it is not expired, a new access token will be issued.
@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. 💯
@rammehar5531
@rammehar5531 2 года назад
Wow great video
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Thank you! 💯
@zakariaamagdy2941
@zakariaamagdy2941 2 года назад
Hey dev, I like you man, your content is amazed me so thank you so much ❤❤, one question if you don't mind, what about making one middleware in the backend checks for access token if it's expired then we check if there's a refresh token and it's valid .then we generate a new access token, instead of making a separate refresh token endpoint, what are the drawbacks of this approach. thanks in advance
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Well thought out question! Your suggestion is possible. However, you may find things differ more as you implement refresh token rotation and reuse detection as in this recent video: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-s-4k5TcGKHg.html - That said, there is more than one way to do this, and your suggestion is worthwhile, too. 💯🚀
@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.
@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.
@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
@gaoo87
@gaoo87 Год назад
Amazing job Dave, I just have a question, once I'm testing the persisting login (min 14:30), it doesn't work with chrome or Edge since the cookie is empty but it works perfectly with Firefox, do you think it can be something related with the addblocker or another plugin? maybe you mentioned in the video but I didn't catch it. Any way, amazing series of videos, I really appreciate the great effort!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Hi Hugo - it should work with Chrome and Edge as well. The cookie should not be empty - it should contain your refresh token. You may have an issue if you set the cookie with secure: true but you are in your dev environment with localhost. It will use "http" and won't support secure: true with requires "https".
@nikolavasic8646
@nikolavasic8646 7 месяцев назад
@@DaveGrayTeachesCode Hi Dave- Chrome wont allow it with SameSite: None and Secure: false. What should we do?
@carolineakesson4546
@carolineakesson4546 2 года назад
Hi Dave, this is really a great series! I just have one question, Im using your way of protected routes that you showed in one other tutorial. The thing is (I'm being bad) Im using local storage, and when I refresh while I am on a protected path the app will lose its context for a split second and send me to the login page although right after the context is back and I can navigate around because Ive collected the auth info from localstorage! Is there any way around this? Can I avoid losing context entirely by checking if user exists in localstorage?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Since you are using localStorage, you might consider loading it at app load time instead (maybe in the index.js) ...I would consider a spinner / loading screen if this was an issue as I waited on a response to a refresh token (without localStorage)
@carolineakesson4546
@carolineakesson4546 2 года назад
@@DaveGrayTeachesCode Thanks! 😁 But how would you go about using the hook useAuth in index.js? Im trying lots of different things but the jist seem to be that it can not be called at the top level?
@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.
@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?
@igmtink
@igmtink 3 месяца назад
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
@ardithastopalli2719
@ardithastopalli2719 2 года назад
Thanks Dave, this is premium content. I just have 1 question, how do we use the privateAxio hook inside the createAsyncThunk? Since it is a hook it can be used only in components. Creating the useAxiosPrivate as a normal function - passing the dispatch function as a callback function from the createAsyncThunk works correctly partly. The problem is because the hook useAxiosPrivate, depends on the auth use selector so it re-runs as soon as the auth data changes. Having it as a normal function,how can we re-fetch the auth access token if it changes - using the get state inside the createAsyncThunk will be triggered only once. Thanks for the knowledge !!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
You're welcome! 🙏 I recommend a slightly different approach with Redux that you will see demonstrated here: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE--JJFQ9bkUbo.html ...if you do want to use Axios with Redux & RTK Query, you can. I did not demonstrate this approach, but it is in the docs here: redux-toolkit.js.org/rtk-query/usage/customizing-queries#axios-basequery
@tomeckstein8566
@tomeckstein8566 Год назад
Hey Dave, great video!! I watched this Video series but now I have a question. In the requireAuth component, we say, if the user has no allowed Role but the auth.user exists then go to unauthorized else login. But in our useRefreshToken Component, we set the Auth to an Object which doesnt hold user anymore. So if i am going to login and vist a page im not allowed to, there comes the login Page not the unauthorized. Is this right or something i have missed? Sorry if my english is not the best, greetings from Germany :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Hi Tom - it has been awhile and I currently don't have time to review and remember it all - but you can change / customize the code any way you want. Overall, this tutorial is to show a concept of how it can work. In my recent MERN series, I implemented this same concept with React / Redux / RTK Query.
@KamrulIslam-wj1ky
@KamrulIslam-wj1ky 2 года назад
Hi Dave, thanks for you great series...I have one question. I've few public route and protected route. I'm persisting protected routes but when browser reloads from public routes my auth state gone that is usual, if i persist public routes then it's working fine but additional API hits every time i reload though I'm not logged in. Can you suggest me the way to avoid API calls when not logged in!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 года назад
Check for your data before calling the API request, and then only allow the API request if there is data you need to check. Another issue may also be noticed with React 18 Strict Mode that now - in development mode only - will mount and unmount every component twice, which may also result in seeing extra API calls.
@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 5 месяцев назад
I also got stuck at the same point. IDK how it worked in his system. I figured it out while watching the video.