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: ruclips.net/p/PL0Zuz27SZ-6M1Uopt6_VL3gf3cpMnwavm
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!
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.
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!
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
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. 😅
Now have seen one of the best if not the best tutorial on RUclips 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 RUclips 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
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?
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?
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.
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.
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.
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.
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.
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?
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.
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.
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!
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.
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!
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.
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?
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.
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 @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.
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
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.
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.
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
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 ?
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.
@@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
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?🙏
@@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.
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: ruclips.net/p/PL0Zuz27SZ-6M1Uopt6_VL3gf3cpMnwavm
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!
Glad it helped!
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.
You're very welcome!
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!
Glad it was helpful and thank you!! 💯🙏
Incredibly helpful. Everything was explained thoroughly. Much appreciated!
Thanks a lot Dave for all the efforts you are putting for us.
What Saket said Dave
You're welcome, Saket!
The video was unbelievably helpful. Thank you so much.
Thanks Dave! All working correctly and up to date. Looking forward to continuing this project with you! Many thanks, Sai
Great work! More to come! 💯
This is probably one of the most useful videos that I have watched in programming journey. Dan, you're such a great teacher !
Thank you! It's Dan D.'s Computer Shop but I'm Dave. 😀
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
I was expecting this course to be a revision of some sort but I have learnt so much
it maybe the must important video in this playlist.
I'm so happy I stumbled upon your channel!
Right on!
Thanks Dave for the great content, always delivering the goods 😎
You're welcome, Ali! 💯
Great tutorial Dave! Can't wait for the front-end implementation with Redux. It's the most confusing part for me :)
That is next! Looking forward to it! 💯
You are excellent teacher!!!!
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. 😅
I suggest refactoring to move sensitive data away from localStorage.
thx dave awesome vid
Thanks for the great content. Keep it up ❤
Great content as always! 💯
Thank you, Annu!
Dave you are amazing! Thank You!
Thank you! 💯
Thank you! You are a great teacher!
You're very welcome!
Thank you very much, you helped me a lot ^^
please make some videos to regard with design patterns and how to use them in both front end and backend , thanks for your contents
Great request! And you're welcome! 💯
thank you
Awesome tutorial thank you very much
You're welcome!
Now have seen one of the best if not the best tutorial on RUclips 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 RUclips 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
Good suggestions! - I have more videos to complete in the series and some of those will use Role Based Access Control / Permissions, too.
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.
Hi Dave, you're a great teacher, is there a possibility to watch some tutorials about Next.js (The React Framework) in the future?
Yes, I plan to make some of those! 💯🚀
You are always superbb
Thank you so much 😀
Very Professional !! Wow
Thank you! 🙏
Thank you!
Welcome!
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?
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?
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.
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.
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.
Awesome👌👌👌👌
Thank you! Cheers!
here i am just using local storage like a 🤡😅 thanks for this insight… i have a few patches to make 🥴
It will be a good update - but don't feel bad. Many use localStorage without knowing about this strategy.
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.
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.
when do this part of the project the response I get in postman is "message": "Unauthorized" Im not sure what I did wrong.
Thank yo.
Welcome!
Don't we need to also store refresh token in db?
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?
@Dave Gray, hi dave should i start by learning your ReactJS crash course and then come back to this MERN project?
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.
@@DaveGrayTeachesCode thank you dave, your tutorials are really awesome, and I think your channel is underrated.
Sir, res.clearCookie is working fine on locally but it's not working on a live server. cookies is not removing
Insure you are matching the cookie settings. Locally does not support https but the live server likely requires it. The secure: true setting.
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.
I can only guess what may be different. Do note that mongoose-sequence dependency doesn't work with the latest mongoose.
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?
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!
what is much better to store authentication header data in client side like in rest api in react, please suggest any package
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.
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!
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.
Yes i tried that before and received the same problem.
After a lot of tries i found the answer for me
Thank you again
@@DaveGrayTeachesCode the timestamp is at minute 30:57
@@TheNoKa how u solved it? I am stuck in same
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?
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.
What happens when the refresh token expires? We have to create an endpoint for that as well.
Yes, and we do. If not in this video, it is definitely soon.
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
you said its MERN Stack project learning, where is React js?
This is lesson 8. I recommend you go through the series in order. React begins around lesson 5.
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
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.
@@DaveGrayTeachesCode yes exactly i mean semi-colon (;) ... anyway good to know I will try to stop using them then as well
@@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.
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
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.
@@DaveGrayTeachesCode Thanks
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.
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.
@@DaveGrayTeachesCode thank you for clearing my doubt. I have understood the concept. It's my misunderstanding of flow of the project.
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
The prerequisite Node.js course covers this in detail. Here is the specific chapter: ruclips.net/video/favjC6EKFgw/видео.html
Thanks sir for your reply
I got it 🙌
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 ?
I inspected the cookie header, here is the value: _ga=GA1.1.2029321707.1662120625. There’s no jwt
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.
@@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
@@okonkwo.ify18 compare to my source code to find the differences. The cookie should be sent.
@@DaveGrayTeachesCode Okay. I will do that right away thanks
"None" should be written in lowercase letters.
res.cookie("jwt", refreshToken, { ... sameSite: "none" })
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?🙏
Browsers will show 401 and 403 errors in the console even if Axios intercepts them.
@@DaveGrayTeachesCode but should it throw 401 error on every reload? Though after a second the correct authHeader gets assigned
@@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.
{2023-03-22}