MERN Stack Authentication with JWT Access, Refresh Tokens, Cookies

แชร์
ฝัง
  • เผยแพร่เมื่อ 30 ก.ค. 2024
  • 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

ความคิดเห็น • 126

  • @DaveGrayTeachesCode
    @DaveGrayTeachesCode  ปีที่แล้ว +5

    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: th-cam.com/play/PL0Zuz27SZ-6M1Uopt6_VL3gf3cpMnwavm.html

  • @msurabhi23
    @msurabhi23 ปีที่แล้ว +5

    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!

  • @sailee5208
    @sailee5208 ปีที่แล้ว

    Thanks Dave! All working correctly and up to date. Looking forward to continuing this project with you! Many thanks, Sai

  • @rjwhite4424
    @rjwhite4424 4 หลายเดือนก่อน

    The video was unbelievably helpful. Thank you so much.

  • @mrbilchalan
    @mrbilchalan ปีที่แล้ว +4

    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.

  • @saketparasher3762
    @saketparasher3762 ปีที่แล้ว +3

    Thanks a lot Dave for all the efforts you are putting for us.

  • @alielb2130
    @alielb2130 ปีที่แล้ว

    Thanks Dave for the great content, always delivering the goods 😎

  • @CKNMEDIA
    @CKNMEDIA 6 หลายเดือนก่อน

    Thanks for the great content. Keep it up ❤

  • @medusa121
    @medusa121 ปีที่แล้ว

    I'm so happy I stumbled upon your channel!

  • @codernerd7076
    @codernerd7076 ปีที่แล้ว +3

    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!

  • @mj2068
    @mj2068 3 หลายเดือนก่อน

    thx dave awesome vid

  • @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 หลายเดือนก่อน +1

      Thank you! It's Dan D.'s Computer Shop but I'm Dave. 😀

  • @diasihammouten4485
    @diasihammouten4485 7 หลายเดือนก่อน

    Thank you very much, you helped me a lot ^^

  • @jozefb.4159
    @jozefb.4159 ปีที่แล้ว +1

    Great tutorial Dave! Can't wait for the front-end implementation with Redux. It's the most confusing part for me :)

  • @ALi-Sloom
    @ALi-Sloom 8 หลายเดือนก่อน

    it maybe the must important video in this playlist.

  • @vladimirjovanovic3540
    @vladimirjovanovic3540 5 หลายเดือนก่อน

    You are excellent teacher!!!!

  • @annusingh4694
    @annusingh4694 ปีที่แล้ว

    Great content as always! 💯

  • @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  ปีที่แล้ว +1

      I suggest refactoring to move sensitive data away from localStorage.

  • @creativestudio2088
    @creativestudio2088 ปีที่แล้ว

    Dave you are amazing! Thank You!

  • @everlastingstudios2467
    @everlastingstudios2467 ปีที่แล้ว

    Thank you! You are a great teacher!

  • @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

  • @sonamohialdin3376
    @sonamohialdin3376 ปีที่แล้ว

    Awesome tutorial thank you very much

  • @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 4 หลายเดือนก่อน

    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?

  • @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.

  • @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

  • @hungnguyencanh5089
    @hungnguyencanh5089 ปีที่แล้ว

    Thank you!

  • @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?

  • @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.

  • @sealuke2724
    @sealuke2724 ปีที่แล้ว

    You are always superbb

  • @pj6206
    @pj6206 ปีที่แล้ว +1

    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  ปีที่แล้ว +6

      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! 💯🚀

  • @ibrahimacanada
    @ibrahimacanada ปีที่แล้ว

    Very Professional !! Wow

  • @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.

  • @gilogilala8475
    @gilogilala8475 ปีที่แล้ว

    Now have seen one of the best if not the best tutorial on TH-cam 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 TH-cam 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  ปีที่แล้ว +4

      Good suggestions! - I have more videos to complete in the series and some of those will use Role Based Access Control / Permissions, too.

  • @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?

  • @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?

  • @dharmeshgohil9375
    @dharmeshgohil9375 ปีที่แล้ว

    Awesome👌👌👌👌

  • @pablo20237
    @pablo20237 ปีที่แล้ว

    Thank yo.

  • @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.

  • @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.

  • @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!

  • @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.

  • @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.

  • @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.

  • @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.

  • @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.

  • @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.

  • @TheNoKa
    @TheNoKa ปีที่แล้ว +1

    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

  • @rumanislam7528
    @rumanislam7528 9 หลายเดือนก่อน

    Sir, res.clearCookie is working fine on locally but it's not working on a live server. cookies is not removing

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  9 หลายเดือนก่อน +1

      Insure you are matching the cookie settings. Locally does not support https but the live server likely requires it. The secure: true setting.

  • @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.

  • @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  ปีที่แล้ว +1

      The prerequisite Node.js course covers this in detail. Here is the specific chapter: th-cam.com/video/favjC6EKFgw/w-d-xo.html

    • @arunkumar-tn5gu
      @arunkumar-tn5gu ปีที่แล้ว

      Thanks sir for your reply

    • @arunkumar-tn5gu
      @arunkumar-tn5gu ปีที่แล้ว

      I got it 🙌

  • @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

  • @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.

  • @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

  • @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  ปีที่แล้ว +1

      @@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}