MERN Stack Authentication with JWT Access, Refresh Tokens, Cookies

Поділитися
Вставка
  • Опубліковано 2 лип 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: ua-cam.com/play/PL0Zuz27SZ-6M1Uopt6_VL3gf3cpMnwavm.html

  • @msurabhi23
    @msurabhi23 Рік тому +4

    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 3 місяці тому

    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.

  • @dnguyendev
    @dnguyendev 8 місяців тому

    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  8 місяців тому

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

  • @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 5 місяців тому

    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!

  • @vladimirjovanovic3540
    @vladimirjovanovic3540 4 місяці тому

    You are excellent teacher!!!!

  • @mj2068
    @mj2068 2 місяці тому

    thx dave awesome vid

  • @ALi-Sloom
    @ALi-Sloom 8 місяців тому

    it maybe the must important video in this playlist.

  • @diasihammouten4485
    @diasihammouten4485 6 місяців тому

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

  • @annusingh4694
    @annusingh4694 Рік тому

    Great content as always! 💯

  • @creativestudio2088
    @creativestudio2088 Рік тому

    Dave you are amazing! Thank You!

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

  • @everlastingstudios2467
    @everlastingstudios2467 Рік тому

    Thank you! You are a great teacher!

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

  • @sonamohialdin3376
    @sonamohialdin3376 Рік тому

    Awesome tutorial thank you very much

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

  • @morgalaksi3835
    @morgalaksi3835 3 місяці тому

    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.

  • @ibrahimacanada
    @ibrahimacanada Рік тому

    Very Professional !! Wow

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

  • @sealuke2724
    @sealuke2724 Рік тому

    You are always superbb

  • @dav.R7
    @dav.R7 Місяць тому

    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?

  • @hungnguyencanh5089
    @hungnguyencanh5089 Рік тому

    Thank you!

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

  • @sprwalrus8749
    @sprwalrus8749 4 дні тому

    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.

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

  • @gilogilala8475
    @gilogilala8475 Рік тому

    Now have seen one of the best if not the best tutorial on UA-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 UA-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?

  • @gergelygalvacsy2251
    @gergelygalvacsy2251 8 місяців тому

    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?

  • @dharmeshgohil9375
    @dharmeshgohil9375 Рік тому

    Awesome👌👌👌👌

  • @pablo20237
    @pablo20237 Рік тому

    Thank yo.

  • @user-vf8bd3mm5n
    @user-vf8bd3mm5n 20 днів тому

    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  19 днів тому

      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.

  • @oleksandraokhotnykova8672
    @oleksandraokhotnykova8672 4 місяці тому

    Don't we need to also store refresh token in db?

  • @CLAUDIAR95
    @CLAUDIAR95 15 днів тому

    when do this part of the project the response I get in postman is "message": "Unauthorized" Im not sure what I did wrong.

  • @chriszertamayo2071
    @chriszertamayo2071 4 місяці тому

    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  4 місяці тому

      I can only guess what may be different. Do note that mongoose-sequence dependency doesn't work with the latest mongoose.

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

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

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

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

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

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

  • @The9ben89
    @The9ben89 Рік тому

    What happens when the refresh token expires? We have to create an endpoint for that as well.

  • @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 8 місяців тому

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

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  8 місяців тому +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.

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

  • @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  Рік тому +1

      The prerequisite Node.js course covers this in detail. Here is the specific chapter: ua-cam.com/video/favjC6EKFgw/v-deo.html

    • @arunkumar-tn5gu
      @arunkumar-tn5gu Рік тому

      Thanks sir for your reply

    • @arunkumar-tn5gu
      @arunkumar-tn5gu Рік тому

      I got it 🙌

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