No video

JWT Authentication | Node JS and Express tutorials for Beginners

  Рет қаралды 113,779

Dave Gray

Dave Gray

Күн бұрын

Web Dev Roadmap for Beginners (Free!): bit.ly/DaveGra...
Learn how to apply JWT Authentication to your Node JS and Express REST API routes in the most secure way possible to avoid XSS and CSRF attacks. This beginners tutorial will help you apply JSON Web Tokens to your REST API built with Node.js and Express.
🚩 Subscribe ➜ bit.ly/3nGHmNn
🚀 This tutorial is part of a Node.js & Express for Beginners tutorial series playlist:
• Node.js Tutorials for ...
🔗 Starter Source Code: github.com/git...
🔗 Completed Source Code: github.com/git...
JWT Authentication | Node JS and Express tutorials for Beginners
(00:00) Intro
(00:05) Welcome
(00:21) JWT Authentication
(03:23) Set up
(03:36) Installing new dependencies
(04:29) Creating environment variables
(07:21) Creating JWT tokens at authorization
(18:14) Creating JWT verification middleware
(21:47) Applying JWT token verification to specific routes
(24:53) Applying JWT token verification to many routes
(28:18) Adding cookie-parser middleware
(29:46) Creating a refresh token controller
(36:03) Creating the refresh route
(36:46) Adding the refresh route to the server
(37:37) Testing the refresh route
(40:03) Creating a logout controller
(48:36) Creating the logout route
(49:26) Adding the logout route to the server
(49:43) A Quick Debug
(50:13) Testing the logout route
(52:43) Frontend: fetch needs the credentials option
(53:29) Backend: CORS needs Access-Control-Allow-Credentials
(56:18) Chrome requires specific cookie options
📚 JWT References:
Intro to JSON Web Tokens: jwt.io/introdu...
All You Need to Know About Storing JWT in the Frontend: dev.to/cotter/...
NPM jsonwebtoken package: www.npmjs.com/...
NPM cookie-parser package: www.npmjs.com/...
Deleting Cookies: expressjs.com/e...
Cross-Site Scripting (XSS): owasp.org/www-...
Cross-Site Request Forgery (CSRF): owasp.org/www-...
REST Security Cheat Sheet: cheatsheetseri...
📚 Login References:
Bcrypt: www.npmjs.com/...
How to Safely Store a Password: codahale.com/h...
MDN: HTTP Response Status Codes: developer.mozi...
📚 More References:
Node.js Official site: nodejs.org
NPM Official site: www.npmjs.com/
Express JS Official site: expressjs.com/
MDN CORS: developer.mozi...
NPM CORS: www.npmjs.com/...
✅ Follow Me:
Twitter: / yesdavidgray
LinkedIn: / davidagray
Blog: yesdavidgray.com
Reddit: / daveoneleven
Was this tutorial about JWT authentication with Node.js and Express JS helpful? If so, please share. Let me know your thoughts in the comments.
#jwt #authentication #node

Пікірлер: 321
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
After initial user authentication. JWTs can be used for verification at REST API endpoints. In this tutorial, you will learn how to issue access and refresh tokens (JWTs), and also the recommended way to issue these tokens for security concerns. There will also be suggestions for storing these tokens in your frontend apps. If you are just starting out with Node.js and Express, I suggest you start at the beginning of the Node.js for Beginners tutorial series here: kzfaq.info/sun/PL0Zuz27SZ-6PFkIxaJ6Xx_X46avTM1aYw
@marcusaureliusregulus2833
@marcusaureliusregulus2833 2 жыл бұрын
So this is how a senior dev works and explains things. Simply amazing. Thank you for these videos.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! 💯
@obiwulugodswill7457
@obiwulugodswill7457 10 ай бұрын
Learnt React from Dave and I contributed to one of my friend's project... bro was amazed at the way I did things.... I now feel like a senior dev
@Uniqlo921
@Uniqlo921 4 ай бұрын
be very careful when testing this specific implementation with nodemon vs a normal server. nodemon restarts after any file changes, including changes to models\users.json. This allows each function to get the updated state of refresh token. If you run this without nodemon, your refresh and logout functions will reference old versions of the users.json data that do not include the refresh token from the auth. This causes some unwanted behavior that took me quite a while to catch. As always, thanks @DaveGrayTeachescode for another great and comprehensive lesson
@Alibeee87
@Alibeee87 2 жыл бұрын
I've been following your tutorials on Node, Express, and working my way to Mongo for my project this week. I've told my professor about how helpful your videos are and I've been spreading the word to my classmates. I'm surprised you don't have more views on these tutorials. Thank you for your help!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Ali! 🙏🙏
@user-cq3ew1ik2q
@user-cq3ew1ik2q 11 ай бұрын
Dude, this is by far the best tutorial series I have seen. Unparalleled quality. Thankyou!
@stevieholland3579
@stevieholland3579 Жыл бұрын
I just wanted to say I appreciate you and what you do. Your videos are well explained, very thorough, but also digestible. Some instructors get a bit too technical, or lack enough technicality to fully understand what is happening. Yours are right in the pocket. Thank you, kind sir. You have provided a lot of clarification for me.
@xifrefont765
@xifrefont765 Жыл бұрын
I usually stay away from tutorials but the content you post is insanely good, I have actually learnt a lot from your channel. Since I discovered it my skills with javascript have improved a lot. Thank you so much
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Awesome! Thank you! 💯
@tabliqatchi6696
@tabliqatchi6696 2 жыл бұрын
This is masterpiece! 😍 I've thanked on all videos of you I've watched in the comments, and I will do it again on this one because you deserve it. Please keep creating content, I'm seriously worried you might lose interest in it at some point and we lose more content created by you, because you're so good.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! I'll keep going! 💯🙏
@ethnical_spyoninstagramist5198
@ethnical_spyoninstagramist5198 Жыл бұрын
I’m so happy to get my account back with help of this professional teams (name on my channel ) kidney massage him now 😮
@susiebaka3388
@susiebaka3388 Жыл бұрын
hey dave this series is really helpful. the way you split things into routers and middleware has been eye-opening. so simple
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad it helped!
@user-te2pe5qm8o
@user-te2pe5qm8o Жыл бұрын
For anyone who doesn't know, if you add secure: true in cookie options, you could only receive cookies on the login route, and in postman couldn't even receive cookies. So test before you add that option.
@thangzathang9100
@thangzathang9100 Жыл бұрын
thank god I came across this comment. helped a bunch ahhah thanks
@dafiraone
@dafiraone Жыл бұрын
Thank you, i got confused in this part
@taiwobabalola4188
@taiwobabalola4188 9 ай бұрын
Thanks it helped. But how do you deal with that in the production enviromment
@DTUSEM
@DTUSEM 3 сағат бұрын
Wrong, for that You need to set PATH in cookie
@camcodes2100
@camcodes2100 10 ай бұрын
Would love to see an updated version with Typescript and maybe with a relational database. These videos are literally the best.
@kakhabervk9405
@kakhabervk9405 Жыл бұрын
I watched many ttorials about jwt because I worked with fullstack php many years and I dont understand rest api so good and This tutorial is where really I did understan about refreshtoken. Thanks
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad it was helpful!
@internet_glen
@internet_glen Жыл бұрын
dave calling out whitelist was the perfect endcap to this great video. dave, my man, youve done it again... another fantastic video
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Glad you enjoyed it!
@user-lw9hx6kk8q
@user-lw9hx6kk8q 3 ай бұрын
probably the most detailed series on the youtube, although really wish you used ts
@edwilsondasilva9946
@edwilsondasilva9946 Жыл бұрын
Hi Dave, Thanks again for sharing this high quality content. Your explanations are excellent.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@ogundekoadegbenga3766
@ogundekoadegbenga3766 Жыл бұрын
Thank you Dave. I read through all the comments and your responses to the questions asked which adds more to what has been learned in the video. Thanks again.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Great to hear! You're welcome!
@shaeebali8445
@shaeebali8445 Жыл бұрын
Thanks Dave, you’re an awesome teacher. Keep it coming please!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thanks, will do!
@wedadgamalelden
@wedadgamalelden 4 ай бұрын
Thank you for nodejs playlist, Your clear explanations and practical examples made the learning process engaging and effective.
@w9914420
@w9914420 2 жыл бұрын
Hi Dave, this is by far far one of the best JWT Authentication videos that I have seen on KZfaq. I was wondering if you have created a frontend for this project. I am interested to know how one would incorporate the refresh route for a seamless experience if for example, I was on a user page that expired how would I refresh the token and regain access to my session without leaving the page? - many thanks
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Great question, Melvyn! And yes, I have very recently. Here is my React Login series that uses the REST API from this Node JS series as the backend: kzfaq.info/sun/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd 🚀🚀🚀🚀
@w9914420
@w9914420 2 жыл бұрын
@@DaveGrayTeachesCode Fantastic! - thanks again
@skillkrio
@skillkrio 9 ай бұрын
Dave in the timeframe 34:00 you are checking the founduser name with the decoded username. I feel it is unnecessary because the cookie contains digital signature which can be regenerated by using the header, payload and secret key present only in the server. The verify method would fails if the cookie signature and generated signature doesn't match. what do you mean by tampering.
@abdulrahmanagboolaosho3582
@abdulrahmanagboolaosho3582 Жыл бұрын
Thanks so much, I just finished your node js course so I was going back to some concepts, I don’t thank you enough
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@learner8084
@learner8084 11 ай бұрын
This is a very valuable video for me. I've been trying to understand how the aT and rT works. Thanks very much
@cinemarat1834
@cinemarat1834 2 жыл бұрын
thanks for putting up these videos dave. hopefully the playlist will be a library for node videos that i can come back to if i need a refresher
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! Glad I could help. 💯
@mikeysauce393
@mikeysauce393 11 ай бұрын
I'm a bit late to this back end party, everything works accept I had to use Postman for the refresh and logout routes. Thanks Dave. 🌮🌮🌮
@kevinspence1771
@kevinspence1771 11 ай бұрын
When I test the refresh route at 38:45 I'm getting a 401 unauthorized response with no cookies available. I've followed along with the first 40 minutes of this tutorial line by line from scratch several times and the refresh route keeps failing. So I also cloned the repo, installed packages, created the .env file, and I still get stuck testing the refresh route with a 401. Dave is the GOAT of youtube coding tutorials, but this one makes me want to run into traffic. I've sunk in far too many hours on this. MOVING ON.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 11 ай бұрын
If you set the cookie secure: true, you must use https. Local dev usually just uses http - other comments here on this, too.
@AdityaDey424
@AdityaDey424 Жыл бұрын
21:19 why you set req.user ? In verifyJWT we are just verifying the access token . If it verified then move forward or else error occur. So for what you set req.user to decoded.UserInfo.username?
@user-xy3zt2pp6i
@user-xy3zt2pp6i 6 ай бұрын
Firstly, congratulations on your clear, detailed and brilliantly explained tutorials. You have rare communications skills. I am working with Node.js Express and MySQL. I have come across express-session and express-mysql-session that store user credentials server side rather than in the users browser as with JWT. Could you develop tutorials on these packages please?
@tobiasfuchs2502
@tobiasfuchs2502 Жыл бұрын
What confuses me most is how to store and work with the refresh tokens in my database (Postgres). My plan is to allow multi-login from different devices for the same user, so my idea is to create a refresh token for each device the user tries to log in with. Each refresh token belongs to a unique device, so I don't care which user belongs to it. That's why my plan is to create a refresh token table with no user references. When a user logs out, I simply remove the respective refresh token from the database and don't care if they are still logged in on other devices. Interesting notes/tips: 1) If a user deleted their cookie, you would end up with "dead tokens" that never get removed from the database. That only applies to multi-login and shouldn't really be a problem though. 2) Deleting all refresh tokens from the database forces all users to relog-in. Same when you change the refresh token secret. Don't do that, unless you have a good reason. 3) Hashing the refresh tokens before storing them in your database improves security. Similarly how you'd store passwords hashed and not in plaintext. 4) bcrypt stores the salt in the generated hash, so you don't need to store salts in your database. 5) You can check if a refresh token expired by catching "TokenExpiredError". Since it's a valid token (just expired), you can safely call jwt.decode(...) to get the username and other information. Not sure where I would need that, but maybe that helps some of you. Edit: Okay, I just realised that when you compare your refresh token with the database (refresh token hash), you run into the problem of not knowing which salt to use for hashing. You either use the same salt all the time, which makes hashing irrelevant, or you store a user reference for each refresh token hash so you know which entries to look at. Then check each hashed refresh token against the provided refresh token and see if one of them matches... Something feels wrong with that approach though, so for the time being, I'll just save the refresh tokens in plaintext. Edit2: Another reason to store the user id with the refrehs token is that when they change their password, we need to invalidate all existing refresh tokens for that user. Otherwise they stay logged in from their other devices as if they never changed their password. It can also be useful to know all user's refresh tokens if you implement some kind of "logout from all devices" functionality. Generally, you need to store the user id if you want to be able to improve security. Without user id, you'd need to decode all refresh tokens and check the user, which is extremely inefficient.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I suggest joining my Discord for bigger discussions like this one: discord.gg/neKghyefqh
@mathewuy527
@mathewuy527 Жыл бұрын
watched from start of the playlist till this video awesome detailed tutorial, thank you very much
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're very welcome!
@jonathantang4429
@jonathantang4429 2 жыл бұрын
Thanks for your videos... I learned a lot from your videos. My thunder client didnt work as per your video. After logging in and getting the access token and the refresh token cookie. when i tried to do the /refresh, the cookie wasn't send together. I got empty cookie. When i use postman, its the same case but i can manually add the refresh token cookie into the request and it works. REALLY appreciate your video, one of the best video out there.
@jonathantang4429
@jonathantang4429 2 жыл бұрын
I just finished your next video on the Roles. you did mentioned that secure need to be removed. Thanks !!1
@kiplaharts5643
@kiplaharts5643 9 ай бұрын
Thanks teacher Dave for making this api totorial availabe,
@rockfox5
@rockfox5 2 жыл бұрын
Hi Dave. Thank you very much. This series have helped me so much.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad I could help! You're welcome! 🙏💯
@juangomez874
@juangomez874 2 жыл бұрын
Wow. Excellent video. Great job. Thanks a lot for doing these tutorials.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you! 💯
9 ай бұрын
Again great video. Thank you very much Dave.
@yashsharma6112
@yashsharma6112 Жыл бұрын
You are awesome. Great videos with a rich content.
@sturmart4076
@sturmart4076 2 жыл бұрын
i have never thought about "whitelist" as something racist
@ufukbalaban434
@ufukbalaban434 Жыл бұрын
It was a great video, thanks Dave !
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Very welcome!
@darshsingh2186
@darshsingh2186 Жыл бұрын
HI Dave, I'm getting status 401 when I try to generate refresh token after generating access token. I tried to console.log('request', req.cookies) and it shows [Object: null prototype] {} in terminal.
@ManweyVideos
@ManweyVideos Жыл бұрын
I needed to modify secure to false in order to have it working in Postman and Thunder Client. res.cookie('jwt', refreshToken, { httpOnly: true, sameSite: 'None', secure: false, maxAge: 24 * 60 * 60 * 1000 }); In comments below there is am answer from Dave "It depends on what you are using to test your endpoints with. In Postman, after you receiving the secure httpOnly cookie with the refresh token, you need to go in and remove the secure: true flag for dev testing. This is because our local dev environment uses http and secure expects https. Or you could just remove the secure: true from the cookie in the code during development - but remember to put it back before deploying."
@afdhaliapreto7703
@afdhaliapreto7703 8 ай бұрын
@@ManweyVideos i'm stil struggling with that until now.. i cant resolve /refresh problem with unauthorized 401
@zineddinelouzani7069
@zineddinelouzani7069 2 жыл бұрын
Great Explanation 😊
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad you liked it!
@elinordeniz
@elinordeniz Жыл бұрын
Thanks a lot. You are gifted for teaching.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you!
@huascar2790
@huascar2790 Жыл бұрын
Wow, very well explained, thank you!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You're welcome!
@chans9055
@chans9055 2 жыл бұрын
What a great tutorial. Thank you. I learned a lot
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! 💯
@danyeun01
@danyeun01 24 күн бұрын
quick question at 45:38 what would happen if the person being iterated through in the database doesnt have a refresh token yet? would the person be filtered through anyway?
@junaidmohammed3148
@junaidmohammed3148 2 жыл бұрын
Hy Dave, I'm stuck in verifyJWT controller, I'm not getting authHeader from the req.headers['authorization']. Any help would be much appreciated please
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
I suggest downloading the source code from the link in the description and comparing to yours to find the differences.
@mohammad._.abohasan
@mohammad._.abohasan Жыл бұрын
Hey Dave! Thank you very much .
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Welcome!
@paulmargerit7682
@paulmargerit7682 Жыл бұрын
Thanks a lot for your videos! It is really helpful!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You are welcome!
@jellyfish1772
@jellyfish1772 2 ай бұрын
Thank you so much!
@sonned9843
@sonned9843 Жыл бұрын
You are the best
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! 🙏
@jakubtomas9154
@jakubtomas9154 2 жыл бұрын
thanks for the tut, quite a good teaching style
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You are welcome! 💯
@yehannk448
@yehannk448 Жыл бұрын
Sir your courses are the best
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you!
@mylastore
@mylastore Жыл бұрын
Just to be clear if the backend and frontend are on the same domain we don't need to set the "Same Site: none".
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Excellent clarification!
@Kazuteru_Nishi
@Kazuteru_Nishi 2 жыл бұрын
hello, when my token is generated and put in cookie, this one is not recovered when I do a refresh which means that I am blocked at this stage... can you help me?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Verify that you are sending the secure: true flag in the cookie. As noted in the tutorial, I had to remove it as ThunderClient did not recognize it.
@huamuhuamu
@huamuhuamu 2 жыл бұрын
@@DaveGrayTeachesCode , It works, Thank you!
@shineLouisShine
@shineLouisShine Жыл бұрын
Thank you very much. 39:16 - I wonder why the refresh doesn't work for me, no matter what. When I call the refresh router with GET - The console logs the same cookie again and again (it doesn't change like in your code) And instead of Status: 200 OK, I get - Status: 403 Forbidden. Furthermore, I did look very very careful for a long long time that our codes are similar. (When I copied your folder and ran your completed code from scratch than it is immediately failed with MODULE_NOT_FOUND message)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Hi Louis - I do not have MODULE_NOT_FOUND message here. If you used my code, did you install the npm package dependencies? Those modules are needed to run the code. You should run: npm update ...that will install the npm package dependencies that are listed in my package.json file.
@shineLouisShine
@shineLouisShine Жыл бұрын
@@DaveGrayTeachesCode Thank you for trying to assist... (1) Regarding my code, after manually copied yours, It is only respond with a "Forbidden" error. What might be the issue? (This is not respond with Status: 200 OK and replacing the cookie "hash number" with every refresh like in your code) (2) Regarding your code (including npm update), logged on the console after running (and crashing) : " Error: secretOrPrivateKey must have a value at Object.module.exports [as sign] (D:\Node-js\express_jwt-main ode_modules\jsonwebtoken\sign.js:107:20) at handleLogin (D:\Node-js\express_jwt-main\controllers\authController.js:21:33) [nodemon] app crashed - waiting for file changes before starting... "
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
@@shineLouisShine looks like you did not create a .env file that holds the secret keys for your access and refresh token creation. Dot env files are not included in Github repositories so you need to create your own. I believe I show how to do this during the video.
@shineLouisShine
@shineLouisShine Жыл бұрын
​@@DaveGrayTeachesCode Wow, I must admit. this is very frustrating. As to my manually written code - I have no idea what is wrong. I certainly wrote the entire code including "process.env.ACCESS_TOKEN_SECRET". Yet, my code isn't respond as your. As to "copypasting" your code, The server doesn't even get connected, only throw this Error: secretOrPrivateKey must have a value. Plus, obviously, each "env" in the code does appear in its correct position, So I'm not entirely understand your kind instruction. So.... I'm completely lost. Totally, desperately, lost.
@shineLouisShine
@shineLouisShine Жыл бұрын
(..I don't know how have I missed this segment.. 🤦‍♂..from 04:45 ) Wow, this is a fascinating deep complicated topic. Thank you for this lesson. There's much much more to read and dig. I must admit, that even after creating the tokens - Yet the refreshing of random cookies one after another such as at your representation - Doesn't work. Should I write anything at the headers fields of Thunder Client? Any key-value pair? Do you have any thought what might be the reason of which it doesn't work yet..?
@js-ny2ru
@js-ny2ru 2 жыл бұрын
This is great! Thank you so much!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Glad it was helpful! And you're welcome! 💯
@teetanrobotics5363
@teetanrobotics5363 Жыл бұрын
you are on god mode, sir !!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
🙏🙏
@tendekay2803
@tendekay2803 2 жыл бұрын
Thank you very much, Dave
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! 💯
@mahendranath2504
@mahendranath2504 2 жыл бұрын
Excellent content, u are very much unique in teaching different scenarios and I’m so impressed , your channel teaches real-time scenarios, create a Udemy courses will be great 👍 , one question can you do a oauth authentication on node, and when do frontend should call refresh token api
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Mahendra! I would need to dive deeper into specific docs for OAuth, but with my understanding, I see no reason what Node.js could not do that. To understand when the frontend will call the refresh token, my React login playlist applies all of that knowledge with the Node.js backend you are building in this series: kzfaq.info/sun/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@mahendranath2504
@mahendranath2504 2 жыл бұрын
@@DaveGrayTeachesCode thank you so much 😊👍🙌🏻👏🤝
@nacerkraa9549
@nacerkraa9549 10 ай бұрын
Thank you so much for your videos
@farzindev
@farzindev 2 жыл бұрын
Great video as always, one question: why we are not saving Access Token in HTTP only Cookie too? then we don't need to attach it to header in front-end. I'm just curious. is there any security reason? becuase it will make it a lot easier for front-end
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Good question! If you are only sending the access token back and not wanting to pull any other data from it, your suggestion could work. If other data is sent inside the access token, JavaScript cannot access a secure httpOnly cookie.
@tallitvak5325
@tallitvak5325 Жыл бұрын
Big Thanks!!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
BIG Welcome!
@mertfromhell
@mertfromhell 4 күн бұрын
whats the voice change at 36:50 got me shooked
@buddikagunawardena2200
@buddikagunawardena2200 Жыл бұрын
This is an awesome video Dave. Many thanks to you! I do have a question as well, what if we want to make the API accessible to the public and also enable validation through cookies? The CORS gets in the way
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You could make _some_ endpoints open to the public and apply JWT auth to the other endpoints. Concerning CORS - which is not part of the JWT auth - you need to decide upfront if open to the public or not. Usually, a publicly available REST API would be created separately from anything that needed to be secure. You may want to Google to see if anyone has mixed the two - but I don't advise it.
@teetanrobotics5363
@teetanrobotics5363 2 жыл бұрын
Sir, you are one of the best on the planet. Could you please make a project video on complete MERN stack and posssibly GraphQL ? Thank you
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, TR 🙏 I do have a MERN project in the works. 💯
@realbapimallick
@realbapimallick 2 жыл бұрын
@@DaveGrayTeachesCode Please update this project with mongoose i.e. MongoDB atlas i.e. Cloud
@suhas-scrobits
@suhas-scrobits 10 ай бұрын
hi dave i am getting this warning "this attemp to set a cookie via set cookie was blocked by user preferance" in incognito mode how can i handle this?? if not handle it will be be fail in incognito mode
@husamburhandev
@husamburhandev Жыл бұрын
Thank you for the excellent video. I have two questions please: 1- Can we depend only on refresh token without the need of generating the access token? 2- Can we depend only on a session token (without the need of jwt) ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You can configure different JWT strategies including a one token approach. It is more often the access token only in that case. You can use a session approach instead of JWTs.
@abdulazeez.98
@abdulazeez.98 Жыл бұрын
Awesome content!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
🙏🙏
@joshua4262
@joshua4262 Жыл бұрын
That refreshToken thing still confuses me. Lets say realtime, and the access token expires in 15 mins, im an admin and can access all the user information, but when the token expires after 15 mins, it obvi that its gonna be 403 even for the admin. in dev, we could manually send the login creditials again, acquire a new access token, paste it in the bearer section and call for the users info again, it gonna show up eventually. But how will we handle this in real time, how will the access token gonna sit automatically and persist when calling these apis from the front end ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You can learn all about the frontend strategy and how the refresh token is used to persist a login in my React Auth playlist: kzfaq.info/sun/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@digitalclub2220
@digitalclub2220 Жыл бұрын
That DB json file took time and complexity more than using an actual mongodb database.
@user-qt4dw6wh3q
@user-qt4dw6wh3q 9 ай бұрын
Hey Dave, Thank you for putting this video with great explanation 👌 I have a question, why did you put `req.user = decoded.username` (21:30)? Since we are not using the username from the request in employeesController functions, should we put decoded username in the request? Please let me know if I am missing something
@jsdevuz
@jsdevuz Жыл бұрын
Why do we need access token? Can't we use the refresh token itself? I did not understand that at all. Isn't it enough if we extend the validity period of the refresh token and send it in the header of every request and check it in the backend?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Refresh token explanation: auth0.com/docs/secure/tokens/refresh-tokens Access token explanation: auth0.com/docs/secure/tokens/access-tokens
@alrazy12
@alrazy12 Жыл бұрын
when we send a get/post request to the protected API we need to set the bearer access token in the cookie so it will be stored in the cookies and vulnerable to XSS or crsf attacks or not like that? what we gained by sending it from the login/refresh API using JSON and storing it in the memory then if we send it back using an authorization bearer token to the API? I'm confused!
@armanbulatovich7341
@armanbulatovich7341 2 жыл бұрын
HI, thanks for video. Great job. Can you tell us about typescript and prisma? thanks.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome! And thanks for the requests! 🙏
@DeepakGupta-hj2dv
@DeepakGupta-hj2dv 2 жыл бұрын
Great explanation Dave ..complete this series? ??
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Almost! Now we just need a database technology like Mongo or Postgres. Adding MongoDB will complete the MERN stack when combined with React.
@DeepakGupta-hj2dv
@DeepakGupta-hj2dv 2 жыл бұрын
Please start new new project mern stack with react with redux
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@DeepakGupta-hj2dv yes, I will be creating projects with this stack.
@divyuesharma
@divyuesharma Жыл бұрын
Hi Dave, I have a question, why do I have to save the token to database? How is that helpful? because you are clearing it from the database, when you created the logout middleware. We can just clear the cookies using the clearCookies as you have done and again we are resetting it to empty string. And is this how authentication done in micro service applications? Or do we pass the token in authorization header in order to access the protected routes? PS - Thanks for making these authentication and authorization series. Loving it. 😍😍.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You don't have to save the refresh token to the database. In fact, many do not and say a benefit of JWT is being "stateless". However, if you want to immediately remove access from someone holding a token, you need to track it. I follow this series up with a JWT Rotation and Re-use Detection video where tokens are also tracked. All in all, more than one JWT strategy exists. Your preference on which to apply.
@divyuesharma
@divyuesharma Жыл бұрын
@@DaveGrayTeachesCode Thanks a lot for the suggestion and I will look into that as well. Thanks for making such a good series. I have been struggling with the authentication part for a long time. This is really helpful. Hope you have a good day. 😊
@haiderjaafer8164
@haiderjaafer8164 2 жыл бұрын
Really great work keep going forward… but if did this with sequelize it’s going to be marvelous… please make lessons on api with sequelize
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thanks for the request! 🙏
@sonamohialdin3376
@sonamohialdin3376 2 жыл бұрын
Amazing tutorial
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Sona!
@m_jdm357
@m_jdm357 11 ай бұрын
Good, gooood.
@kove5762
@kove5762 Жыл бұрын
43:31 If there's no JWT cookie during logout, shouldn't we send one of 400 codes? Like 401- Unauthorized?
@AmitKumar-cp6mx
@AmitKumar-cp6mx 8 ай бұрын
What's the purpose of frequently issuing accessToken when we can send accessToken in cookie (http:only) with a defined age and whenever we user want to log out we can clear the cookie from server I mean why to issue refresh token? We can achieve the purpose without it Please explain
@saeidm4884
@saeidm4884 6 ай бұрын
We need to issue access tokens frequently because we set them to expire after a short time to improve security of our app. If you don't use refresh tokens, then you should increase life span of access tokens so they don't expire often.
@AdityaDey424
@AdityaDey424 Жыл бұрын
Why do you add random access and refresh token in .env file? Or what happens if we set the ACCESS & REFRESH token to "" ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I thought I explained why I did? For "what happens if" questions.. I always say try it :)
@MistikKurabiye
@MistikKurabiye 2 жыл бұрын
excellent job sir.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you for the kind words! 🙏
@tjans1979
@tjans1979 6 ай бұрын
Help me understand something. Say I authorize by hitting the auth endpoint, get a jwt and a refresh token, and the jwt from auth gets stored in memory in my app. Later, I request a protected endpoint, say a list of employees. I send the api request to get the employees, and that endpoint determines I am expired and therefore grabs a new auth token, I obviously need to get that new auth token from the response to store in my application. Does that mean that every request to every protected endpoint has to return an auth token, which is either the existing one that hasn't expired, or the one that was created from the refresh token?
@tjans1979
@tjans1979 6 ай бұрын
Apparently this can be handled with axios interceptors?
@mpbasics8285
@mpbasics8285 Жыл бұрын
I'm getting stocked at the refresh route part....I'm using thunderbolt to send the get request....it doesn't seem to ever resolve and the process keeps loading....and there are no errors thrown
@manuelmartin6132
@manuelmartin6132 Ай бұрын
The secure: true flag for dev testing works right using Postman but not using Thunder Client 😊
@Matt-db7ky
@Matt-db7ky Жыл бұрын
Thank you so much. Do you have a starting point for how I can intercept request/response using fetch rather than axios?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Fetch and Axios are usually in frontend apps and this video is about Node.js and the backend REST API. I do cover fetch with async / await here: kzfaq.info/get/bejne/jNOBacd529SveYE.html
@suvethabalakumar589
@suvethabalakumar589 10 ай бұрын
When I try get request for refresh ,I'm getting unauthorized.
@miratorimoonlight7738
@miratorimoonlight7738 2 жыл бұрын
Thank you very much for this awesome tutorial, Dave. I have a question though. We only delete refresh token when user logs out. Does that mean "if some bad guy has access to the user's access token, they still can access protected route for a while before it expires"?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
The access token should only be stored in memory (state) on the frontend and should also have a short expiration (15 to 60 minutes - set to preference). In theory though, yes, if someone steals an access token and it is not expired, it will provide access. The undeniable truth: Nothing is 100% secure in the frontend.
@jeetudewangan9836
@jeetudewangan9836 Жыл бұрын
You have to delete accessToken also on logout because suppose you have given 5 min expiry to the accessToken and then you logout before expired accessToken but in your tutorial you have delete only refreshToken but accessToken still exists so user can still access APIs before expired accessToken. If I'm wrong please correct me
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You certainly can if you want to. Given what should be a short lifespan, you can also just let them expire.
@jeetudewangan9836
@jeetudewangan9836 Жыл бұрын
@@DaveGrayTeachesCode OK i understood thanks for your reply
@darshsingh2186
@darshsingh2186 Жыл бұрын
At 23:00 while trying to test auth route after protecting with token, I'm getting an error. Error: secretOrPrivateKey must have a value at module.exports [as sign] (C:\GemReactDemo\server ode_modules\jsonwebtoken\sign.js:105:20) at handleLogin (C:\GemReactDemo\server\controllers\authController.js:21:33)
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
The error indicates you do not have a value for secretOrPrivateKey. Go back and find where I set that.
@darshsingh2186
@darshsingh2186 Жыл бұрын
@@DaveGrayTeachesCode hey Dave thanks for replying. I triple checked each letter of the code to no avail. However the error resolved itself when I console.logged access and refresh tokens. Idk why it started working but it did. Left me confused as hell
@darshsingh2186
@darshsingh2186 Жыл бұрын
@@DaveGrayTeachesCode HI Dave, I'm getting status 401 when I try to generate refresh token after generating access token. I'm unable to generate refresh token. Please help.
@avelon9629
@avelon9629 Жыл бұрын
thnks for the video Dave, i had a question what if i want to revoke a user from accessing secure resources from API what would i need to do ? just remove that refresh token of user from DB immediately ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Yes. If using user roles, remove or disable those, too. A short lived access token - 15 minutes for example - would likely expire soon enough but also applying user roles will allow you to remove access faster.
@avelon9629
@avelon9629 Жыл бұрын
@@DaveGrayTeachesCode it seems like i need to create another middleware that checks for roles and perform this checking over there , right now its just token verification as you told in the video.
@kennyw886
@kennyw886 Жыл бұрын
30:00 I don't understand which part in the refresh token allows it to create another access token when it is expired, can anyone explain for me?
@thebowshock7729
@thebowshock7729 Жыл бұрын
Hello, doesn't setting a refresh token cookie violate the REST Stateless principle in this case?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
That usually refers to not storing it in the backend database - which is just one approach because it does not have to be stateless. For example, tracking tokens for re-use detection and rotation. However, you are referring to the frontend. If you want to be able to log back in after a refresh, you'll need to store it somewhere like a secure httpOnly cookie or localStorage - but the latter is not secure.
@thebowshock7729
@thebowshock7729 Жыл бұрын
@@DaveGrayTeachesCode Thank you for your reply and detailed quality explanation. Just one question- is that cookie effectively set in the backend (rest api in this case) or is it just packaged in the backend to be actually set and used in the front end?
@bryanmurasira9682
@bryanmurasira9682 Жыл бұрын
how does the access token in the auth header change when we use the refreshtoken handler?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
This video is about the backend so we just handle what is sent. It sounds like you are asking about how to _send_ the different tokens - and that is a frontend question answered here: kzfaq.info/get/bejne/pK9og7yLs6zYkZc.html
@cerritosrules
@cerritosrules Жыл бұрын
If I were using MongoDB as my database, would I need to add a refreshToken field in the mongoose schema?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Not unless you are storing it. Many do not store JWT tokens as they wish to keep that process "stateless". However, I do store some tokens in this series because I continue on to show a strategy that applies token re-use detection.
@danielnieto5356
@danielnieto5356 Жыл бұрын
Great tutorial, thanks a lot. I hava just one question, why don't you use Passport JS for authentication? I say that because I saw Passport JS is frecuently used for this
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Passport JS can be used for auth. Why didn't I use it? It is not the only solution and not what I created the tutorial about.
@kyawswarhein9657
@kyawswarhein9657 Жыл бұрын
Is there any other video that comes after that? I don't know how to use with front end. 😢
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
This is a Node.js video series which builds the backend. One example of a React frontend that uses this Node.js code as the backend is here: kzfaq.info/sun/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@user-pd9nh4le1l
@user-pd9nh4le1l Жыл бұрын
can I ask you how can the frontend gonna know when to call the refresh API .. waiting your answer please
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Depends on how you build the frontend. The backend should be a separate concern. One example of a frontend is built in this playlist: kzfaq.info/sun/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@vramosjd
@vramosjd Жыл бұрын
Hello Dave, by the end of the video you showed a frontend app, will you show how to code that in the next videos of this series? Also, are you going to show in the next videos of this series how to use the /refresh route automatically? Because if my understanding is correct, the /refresh route in this video's code will not run automatically, right?
@yassineoh813
@yassineoh813 Жыл бұрын
kzfaq.info/get/bejne/pK9og7yLs6zYkZc.html
@kana-test4375
@kana-test4375 Жыл бұрын
Hello Dave. Is it neccesary to store refresh token in DB? In other tutorial you skipped this step. Thanks in advance for response
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
No it is not. In face, many prefer the stateless nature of JWTs. However, I have a tutorial on refresh token rotation and for that, you do need to keep track of tokens.
@kana-test4375
@kana-test4375 Жыл бұрын
@@DaveGrayTeachesCode BTW thank you for your awesome work! U should be awarded Nobel Prize :D
@shineLouisShine
@shineLouisShine Жыл бұрын
Thank you very much again. 59:20 - Is it possible that after the last changes which have been made to the code - The "GET refersh" call is no loger refresh the cookies, and respond only with "401 Unauthorized"..?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
No, everything works for me at that point. Insure your refresh token is set to last long enough that it is not expiring. Are you logging the value of the refresh token when it is received at that endpoint? That will tell you if it is really receiving a value or not. When you have a problem, you have to eliminate each possibility one-by-one until you find the cause before it can be fixed.
@tejass817
@tejass817 2 жыл бұрын
Great content
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
Thank you, Tejas! 🙏💯
NGINX Tutorial - What is Nginx
14:32
TechWorld with Nana
Рет қаралды 87 М.
Fast and Furious: New Zealand 🚗
00:29
How Ridiculous
Рет қаралды 48 МЛН
女孩妒忌小丑女? #小丑#shorts
00:34
好人小丑
Рет қаралды 7 МЛН
Get 10 Mega Boxes OR 60 Starr Drops!!
01:39
Brawl Stars
Рет қаралды 10 МЛН
Why is anti-immigration sentiment on the rise in Canada?
13:00
The Guardian
Рет қаралды 1,7 МЛН
What Is JWT and Why Should You Use JWT
14:53
Web Dev Simplified
Рет қаралды 1,1 МЛН
Session vs Token Authentication in 100 Seconds
2:18
Fireship
Рет қаралды 1 МЛН
JWT Authentication Tutorial - Node.js
27:36
Web Dev Simplified
Рет қаралды 1 МЛН
Fast and Furious: New Zealand 🚗
00:29
How Ridiculous
Рет қаралды 48 МЛН