Тёмный

MERN Stack Authentication with JWT Access, Refresh Tokens, Cookies 

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

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGrayWebDevRoadmap
Learn MERN Stack Authentication and Authorization with JWT Access & Refresh Tokens and secure cookies. Create auth routes and an auth controller for a REST API that will handle authentication and issue JWT tokens for valid users.
💖 Support me on Patreon ➜ / davegray
⭐ Become a full-stack web dev with Zero To Mastery Courses:
- Advanced React & Redux: bit.ly/AdvReactDev
- The Complete Node.js Developer: bit.ly/CompleteNodeJS
- Jr to Senior Web Dev Roadmap: bit.ly/WebDevRoadmap-JrtoSr
🚩 Subscribe ➜ bit.ly/3nGHmNn
📬 Course Updates ➜ courses.davegray.codes/
🚀 Discord ➜ / discord
☕ Buy Me A Coffee ➜ www.buymeacoffee.com/davegray
👇 Follow Me On Social Media:
Github: github.com/gitdagray
Twitter: / yesdavidgray
LinkedIn: / davidagray
🔗 All Resources for this MERN Stack Project: github.com/gitdagray/mern_sta...
🔗 Playlist for this MERN Stack Project Series: bit.ly/3Sn4EaI
MERN Stack Authentication with JWT Access, Refresh Tokens, Cookies
(00:00) Intro
(00:09) Welcome
(00:22) Quick lessons recap
(00:55) Authentication vs Authorization
(01:49) Starter Code
(02:12) Add auth routes to server
(02:42) Auth routes router
(04:26) Rate limiting middleware
(07:47) Auth controller
(10:07) Adding controller methods to auth routes
(11:01) Understanding the JWT auth process
(13:13) Create token secrets with Node.js
(15:34) login method in auth controller
(20:13) refresh method in auth controller
(22:31) logout method in auth controller
(23:29) Create middleware to verify JWTs
(26:51) Apply verifyJWT middleware to routes
(28:44) Test the login endpoint with Postman
(31:23) Test the refresh endpoint with Postman
(32:33) Test the logout endpoint with Postman
(33:15) Test the verifyJWT middleware with Postman
📚 Suggested Pre-requisites for this MERN course:
🔗 Node.js for Beginners full course: • Node.js Full Course fo...
🔗 React JS for Beginners full course: • React JS Full Course f...
🔗 Redux Toolkit for Beginners full course: • React Redux Full Cours...
🔗 React Login Playlist: • React Login, Registrat...
📚 Tutorial References:
🔗 Express Rate Limiter: www.npmjs.com/package/express...
🔗 jsonwebtoken: www.npmjs.com/package/jsonweb...
Was this MERN Stack Authentication tutorial helpful? If so, please share. Let me know your thoughts in the comments.
#mern #stack #authentication

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

 

5 авг 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 126   
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Part 8 of The MERN Stack Project Series - In this lesson, we begin the process of adding Authentication and Authorization to our MERN Stack Project. We will apply the auth routes, auth controllers, and middleware to our backend REST API which will handle authentication, authorization, and JWT verification. This tutorial is not for beginners. If you are a beginner, check out my full courses all in one playlist here: ru-vid.com/group/PL0Zuz27SZ-6M1Uopt6_VL3gf3cpMnwavm
@msurabhi23
@msurabhi23 Год назад
The layout of this tutorial and lesson 1-4 on how routes, controller and middleware are put together is amazing. I have gone through the the nodejs tutorial suggested too. That was a big help. But thanks to this one , the concepts are so crisp and clear. Thank you for doing these tutorials. Keep posting!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad it helped!
@rjwhite4424
@rjwhite4424 5 месяцев назад
The video was unbelievably helpful. Thank you so much.
@sailee5208
@sailee5208 Год назад
Thanks Dave! All working correctly and up to date. Looking forward to continuing this project with you! Many thanks, Sai
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Great work! More to come! 💯
@mrbilchalan
@mrbilchalan Год назад
After or before developing any site, every developer fear about the sites security. At least backend developer. You teach us a lot about security. Its a big issue that how and when to logged any vulnerable users info. Keep it up and thank you.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're very welcome!
@CKNMEDIA
@CKNMEDIA 6 месяцев назад
Thanks for the great content. Keep it up ❤
@alielb2130
@alielb2130 Год назад
Thanks Dave for the great content, always delivering the goods 😎
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome, Ali! 💯
@saketparasher3762
@saketparasher3762 Год назад
Thanks a lot Dave for all the efforts you are putting for us.
@ArcticPrimal
@ArcticPrimal Год назад
What Saket said Dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome, Saket!
@medusa121
@medusa121 Год назад
I'm so happy I stumbled upon your channel!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Right on!
@diasihammouten4485
@diasihammouten4485 7 месяцев назад
Thank you very much, you helped me a lot ^^
@dnguyendev
@dnguyendev 9 месяцев назад
This is probably one of the most useful videos that I have watched in programming journey. Dan, you're such a great teacher !
@DaveGrayTeachesCode
@DaveGrayTeachesCode 9 месяцев назад
Thank you! It's Dan D.'s Computer Shop but I'm Dave. 😀
@codernerd7076
@codernerd7076 Год назад
Wow, you went above and beyond on this one by showing how to create secure secrets for the tokens! Almost everyone skips that! Thank you! Can't wait for the next part! Would be more than happy to buy any paid course from you in the future if you make one someday!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad it was helpful and thank you!! 💯🙏
@mj2068
@mj2068 3 месяца назад
thx dave awesome vid
@vladimirjovanovic3540
@vladimirjovanovic3540 5 месяцев назад
You are excellent teacher!!!!
@ALi-Sloom
@ALi-Sloom 9 месяцев назад
it maybe the must important video in this playlist.
@annusingh4694
@annusingh4694 Год назад
Great content as always! 💯
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you, Annu!
@creativestudio2088
@creativestudio2088 Год назад
Dave you are amazing! Thank You!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you! 💯
@everlastingstudios2467
@everlastingstudios2467 Год назад
Thank you! You are a great teacher!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're very welcome!
@jozefb.4159
@jozefb.4159 Год назад
Great tutorial Dave! Can't wait for the front-end implementation with Redux. It's the most confusing part for me :)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
That is next! Looking forward to it! 💯
@sonamohialdin3376
@sonamohialdin3376 Год назад
Awesome tutorial thank you very much
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You're welcome!
@leoMC4384
@leoMC4384 Год назад
Very useful. I'm a backend developer working on a hobby full stack project with React and I'm using local storage for the token on my frontend which I know it's a bad practice but it was the one that worked when I started this many months ago. 😅
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I suggest refactoring to move sensitive data away from localStorage.
@sprwalrus8749
@sprwalrus8749 Месяц назад
Thanks a lot for the content Dave ! Just a little question : is it mandatory to apply the verifyJWT middleware on post request to create a new user ? It returns on error because as far as there isn't any token created, it's impossible to register.
@dav.R7
@dav.R7 2 месяца назад
Thanks Dave for the tutorial. I have a question. In the accessToken validation middleware, wouldn't it be good to check if the refreshToken is in the cookie?
@lalojejeje
@lalojejeje 5 месяцев назад
Hi there, Dave! Thanks for your tutorials, they are awesome! I have a question, when you logout, but you haven't refreshed it, you can't go to '/', there's an error in here, how can I resolve it?
@abdulrahmanagboolaosho3582
@abdulrahmanagboolaosho3582 Год назад
JWT didn't really make sense in the node js course, because I had not watched the react auth course but now that I have watched it and I have seen this video all the things that didn't make sense are starting to addup , thank you soo mush for your continuous efforts
@abdulrahmanagboolaosho3582
@abdulrahmanagboolaosho3582 Год назад
I was expecting this course to be a revision of some sort but I have learnt so much
@hungnguyencanh5089
@hungnguyencanh5089 Год назад
Thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Welcome!
@gergelygalvacsy2251
@gergelygalvacsy2251 9 месяцев назад
If I have a lot of endpoints that I only want the admin user to access (as opposed to regular users who are free to sign up and log in), would it make sense to create an additional admin access token, just to make sure no one else uses those endpoints?
@ibrahimacanada
@ibrahimacanada Год назад
Very Professional !! Wow
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you! 🙏
@sealuke2724
@sealuke2724 Год назад
You are always superbb
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you so much 😀
@morgalaksi3835
@morgalaksi3835 4 месяца назад
Thanks for the tutorial a lot. I couldn't get why we did not give refresh token too after login to the user but only accessToken.
@pj6206
@pj6206 Год назад
Hi Dave! thanks for sharing such resourceful materials! I've seen videos on JWT authentication in both node JS and MERN stack playlist but I'm not quite sure if I got the whole concept. I googled it and read some articles but I'm not quite sure if I digested the concept properly. Do you have any tutorial on the flowchart of this processes?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I do not have more than what you have seen here and in my Node.js course. You have given me a great idea though! I should make a flowchart for download! 💯🚀
@CLAUDIAR95
@CLAUDIAR95 Месяц назад
when do this part of the project the response I get in postman is "message": "Unauthorized" Im not sure what I did wrong.
@shayanhdry6224
@shayanhdry6224 Год назад
please make some videos to regard with design patterns and how to use them in both front end and backend , thanks for your contents
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Great request! And you're welcome! 💯
@SaurabhSingh-en3iv
@SaurabhSingh-en3iv Год назад
MongoServerError: FieldPath cannot be constructed w ith empty string m geting this error in get/users or get /notes can any one explain why t
@oleksandraokhotnykova8672
@oleksandraokhotnykova8672 5 месяцев назад
Don't we need to also store refresh token in db?
@desarrolloklksistemas3928
@desarrolloklksistemas3928 Год назад
Hi Dave, you're a great teacher, is there a possibility to watch some tutorials about Next.js (The React Framework) in the future?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Yes, I plan to make some of those! 💯🚀
@chriszertamayo2071
@chriszertamayo2071 5 месяцев назад
Hi Dave in chapter 7 in route "/dash/notes/new" when i tried to refresh the page(form) there's an error "id undefined" which refers to user[0].id and i already compared my code to yours not sure why it's undefined but whenever i do save the code the value appears in console and then same error appears again when i refresh the page.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 5 месяцев назад
I can only guess what may be different. Do note that mongoose-sequence dependency doesn't work with the latest mongoose.
@gilogilala8475
@gilogilala8475 Год назад
Now have seen one of the best if not the best tutorial on RU-vid that's up to (Laravel role based access control ) using MongoDB Node.js and React.js. that's what people that are coming from a PHP background is looking for, this is an Enterprise level system that no body on RU-vid as done. thanks we are very grateful and I thank you should change the title to ( MERN Stack Authentication with JWT Access, Refresh Tokens, Cookies , Role Based Access Control ) or ( MERN Stack Authentication with JWT , Role Based Access Control, Cookies ) so it will be easy for people to fine
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Good suggestions! - I have more videos to complete in the series and some of those will use Role Based Access Control / Permissions, too.
@user-vf8bd3mm5n
@user-vf8bd3mm5n Месяц назад
Hi sir Dave! I'm struggling with implementing auth in Next.js so I came back to watch the Mern stack Auth series you made. Do you think this auth workflow will work with Next.js because I ditch next-auth since refresh token with their credentials provider is too hard to implement.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Месяц назад
This could work but there would need to be some changes for next.js and server components overall. I've been using Kinde for auth because it is very easy to implement and support the app router.
@dharmeshgohil9375
@dharmeshgohil9375 Год назад
Awesome👌👌👌👌
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Thank you! Cheers!
@mrfirstname578
@mrfirstname578 Год назад
hello dave is this code ready for production aplication? If i use next js recomedation to use library next-auth or make our own authentication?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
This series is not yet complete. In the next few lessons, the series will complete the login authentication, JWT authorization, and Role-based access control / permissions. Also deployment. More to come!
@pablo20237
@pablo20237 Год назад
Thank yo.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Welcome!
@mahdisalmanizadegan5595
@mahdisalmanizadegan5595 Год назад
@Dave Gray, hi dave should i start by learning your ReactJS crash course and then come back to this MERN project?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Yes, in the first video of this series I discuss what I think the prerequisites are and I link to them in the description of all of the videos. This includes React, Redux, and Node.js.
@mahdisalmanizadegan5595
@mahdisalmanizadegan5595 Год назад
@@DaveGrayTeachesCode thank you dave, your tutorials are really awesome, and I think your channel is underrated.
@stranger_vlog_tv
@stranger_vlog_tv Год назад
Hello Mr. Dave i was finished this chapter, i have one question why i can still fetch the users list and the notes list eventhough i hit the logout button and clear the cookies at postman?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Answer: Something is different in your code from mine. Check the course resource link for the completed source code and compare to yours for differences.
@ABUTAHER-wg7gz
@ABUTAHER-wg7gz Год назад
what is much better to store authentication header data in client side like in rest api in react, please suggest any package
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I am not sure I understand your question. In this project, we do store auth data in the client state. We also use a secure http only cookie to store the refresh token in the client (browser). The REST API is on the backend and processes the tokens but for this project, we kept it stateless. It does not store auth data.
@rumanislam7528
@rumanislam7528 10 месяцев назад
Sir, res.clearCookie is working fine on locally but it's not working on a live server. cookies is not removing
@DaveGrayTeachesCode
@DaveGrayTeachesCode 10 месяцев назад
Insure you are matching the cookie settings. Locally does not support https but the live server likely requires it. The secure: true setting.
@willyhorizont8672
@willyhorizont8672 Год назад
I love this series 🚀 Do you have any plan to deploy MERN stack app to windows server IIS Dave? I have a server rack in office where I work and a guy who deploy my app. But I want to know my self how to deploy MERN stack app.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Glad to hear that Willy! No plans to deploy to a Windows server. I'll use one of several freely accessible hosts so viewers can do the same. You can deploy to a Windows IIS server though. I think you can find some step-by-step articles for IIS.
@The9ben89
@The9ben89 Год назад
What happens when the refresh token expires? We have to create an endpoint for that as well.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Yes, and we do. If not in this video, it is definitely soon.
@TheNoKa
@TheNoKa Год назад
Hey Dave! Your guides are awesome! Thank you In my code based on your code I have a problem I hope you can help me The refresh token in the browser doesn't work (http code 401 token not even found) but in postman it works perfectly I tried setting my server and frontend to https because I know when cookies are set sameSite none, the scure must be true and must be https And it still doesn't work what am i missing here? Thanks in advance!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Somewhere in this tutorial - I don't know the timestamp - but somewhere in here I note that you will need to remove the secure: true flag from the cookie after you receive it in order to send it back in your local dev environment. Your local dev environment will just run with http.
@TheNoKa
@TheNoKa Год назад
Yes i tried that before and received the same problem. After a lot of tries i found the answer for me Thank you again
@draicor
@draicor Год назад
@@DaveGrayTeachesCode the timestamp is at minute 30:57
@tusharprajapati9290
@tusharprajapati9290 Год назад
​​@@TheNoKa how u solved it? I am stuck in same
@BhaumikDhameliya
@BhaumikDhameliya Год назад
hi there, there is one issue in our app, we have applied middleware to our userRoute but we have to exclude the new user route otherwise user can not create account it says unauthorized.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
This is not an issue, but good job identifying something you should do during development - and that is, create an admin user with Postman before adding the verifyJWT middleware. You can see in this tutorial and previous tutorials that I had already created a few users including a user for our stakeholder, Dan D., who is an admin. Only the roles of admins and managers should be able to create new users when we finish the project and users will need to be logged in and verified in order to do so.
@BhaumikDhameliya
@BhaumikDhameliya Год назад
@@DaveGrayTeachesCode thank you for clearing my doubt. I have understood the concept. It's my misunderstanding of flow of the project.
@shankardakolia4912
@shankardakolia4912 Год назад
I am facing issue in mongodb rest api i have two collections income and expense i want and endpoint with calculated fields Total Income, Total Expense and Current Balance
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
You can calculate those totals in Node.js after you receive the data from MongoDB and then you can send it to your frontend app in a response.
@shankardakolia4912
@shankardakolia4912 Год назад
@@DaveGrayTeachesCode Thanks
@arunkumar-tn5gu
@arunkumar-tn5gu Год назад
Sir how is that verifyJWT middleware works ? We are not comparing the decoded value in the controller .. Iam confused.... Could anyone tell me? Sorry my English is not good
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
The prerequisite Node.js course covers this in detail. Here is the specific chapter: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-favjC6EKFgw.html
@arunkumar-tn5gu
@arunkumar-tn5gu Год назад
Thanks sir for your reply
@arunkumar-tn5gu
@arunkumar-tn5gu Год назад
I got it 🙌
@seightan
@seightan Год назад
here i am just using local storage like a 🤡😅 thanks for this insight… i have a few patches to make 🥴
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
It will be a good update - but don't feel bad. Many use localStorage without knowing about this strategy.
@okonkwo.ify18
@okonkwo.ify18 Год назад
Hey Dave. I have a problem my react app does not send cookies when I request the refresh token endpoint with withCredentials set to true. But thunderClient does. Any idea why ?
@okonkwo.ify18
@okonkwo.ify18 Год назад
I inspected the cookie header, here is the value: _ga=GA1.1.2029321707.1662120625. There’s no jwt
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Have you verified that your frontend is receiving the cookie to begin with? If you have the secure: true flag set in the cookie and you are using localhost in your dev environment it has "http" instead of "https" and that will not allow the cookie.
@okonkwo.ify18
@okonkwo.ify18 Год назад
@@DaveGrayTeachesCode yes I removed d secure option after some research and After login the cookie is set to JWT. But subsequent requests don’t send the cookie
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
@@okonkwo.ify18 compare to my source code to find the differences. The cookie should be sent.
@okonkwo.ify18
@okonkwo.ify18 Год назад
@@DaveGrayTeachesCode Okay. I will do that right away thanks
@hosamgnaba3205
@hosamgnaba3205 Год назад
dave my friend, is it a bad habit to keep the comma at the end of the line .... i still using them all the time
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
I think you are asking about the semi-colon which looks like this ; I have previously used them all the time as it was how I learned JS. However, I am more frequently seeing code examples without them, and they are not necessary.
@hosamgnaba3205
@hosamgnaba3205 Год назад
@@DaveGrayTeachesCode yes exactly i mean semi-colon (;) ... anyway good to know I will try to stop using them then as well
@draicor
@draicor Год назад
@@hosamgnaba3205 @Dave Gray just because javascript has Automatic Semicolon Insertion does not mean we should abuse it, the compiler is adding every semicolon we skip to 'fix' our code before execution.. Anyway, another amazing tutorial Mr. Gray, thank you so much for taking the time to develop this.. Anyone learning javascript should binge every single one of your playlists, they are pure gold.
@mthcreativeworld5049
@mthcreativeworld5049 Год назад
you said its MERN Stack project learning, where is React js?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
This is lesson 8. I recommend you go through the series in order. React begins around lesson 5.
@webcoder293
@webcoder293 Год назад
24:33 if (!authHeader?.startsWith('Bearer ')) return res.status(401).json({ message: 'Unauthorized' }) Everytime I refresh a page, first I get 401 unauthorized error and authHeader is undefined. After a second it automatically gets the correct value. It's not affecting the site, but on every refresh 401 axios error appearing on console which is very irritating. Have not found any solution on internet. Can you pls explain why this is happening and how to get rid of it?🙏
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
Browsers will show 401 and 403 errors in the console even if Axios intercepts them.
@webcoder293
@webcoder293 Год назад
@@DaveGrayTeachesCode but should it throw 401 error on every reload? Though after a second the correct authHeader gets assigned
@DaveGrayTeachesCode
@DaveGrayTeachesCode Год назад
@@webcoder293 if I remember correctly, yes. It needs the 401 to intercept it and then send the refresh token. You wipe the state with a reload. I think I explain this in the video? For further info, watch the React Auth series playlist on my channel.
@alexshepel9387
@alexshepel9387 Год назад
"None" should be written in lowercase letters. res.cookie("jwt", refreshToken, { ... sameSite: "none" })
@Pareshbpatel
@Pareshbpatel Год назад
{2023-03-22}
Далее
Китайка Шрек всех Сожрал😂😆
00:20
Authentication & Refreshing Tokens Implementation
2:09:53
What Is JWT and Why Should You Use JWT
14:53
Просмотров 1,1 млн
Difference between cookies, session and tokens
11:53
Просмотров 610 тыс.
Refreshing Tokens With Axios Interceptors
39:55
Просмотров 88 тыс.
JWT Authentication Tutorial - Node.js
27:36
Просмотров 1 млн