JWT Authentication | Node JS and Express tutorials for Beginners

  Рет қаралды 117,840

Dave Gray

Dave Gray

Күн бұрын

Пікірлер: 326
@DaveGrayTeachesCode
@DaveGrayTeachesCode 3 жыл бұрын
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: kzbin.info/aero/PL0Zuz27SZ-6PFkIxaJ6Xx_X46avTM1aYw
@sturmart4076
@sturmart4076 2 жыл бұрын
i have never thought about "whitelist" as something racist
@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 11 ай бұрын
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
@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! 🙏🙏
@安全保密
@安全保密 Жыл бұрын
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 10 ай бұрын
Thanks it helped. But how do you deal with that in the production enviromment
@DTUSEM
@DTUSEM Ай бұрын
Wrong, for that You need to set PATH in cookie
@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 😮
@skillkrio
@skillkrio 10 ай бұрын
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.
@Uniqlo921
@Uniqlo921 6 ай бұрын
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
@WilliamBurroughs-q3b
@WilliamBurroughs-q3b Жыл бұрын
Dude, this is by far the best tutorial series I have seen. Unparalleled quality. Thankyou!
@w9914420
@w9914420 2 жыл бұрын
Hi Dave, this is by far far one of the best JWT Authentication videos that I have seen on KZbin. 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: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd 🚀🚀🚀🚀
@w9914420
@w9914420 2 жыл бұрын
@@DaveGrayTeachesCode Fantastic! - thanks again
@camcodes2100
@camcodes2100 Жыл бұрын
Would love to see an updated version with Typescript and maybe with a relational database. These videos are literally the best.
@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?
@edwilsondasilva9946
@edwilsondasilva9946 2 жыл бұрын
Hi Dave, Thanks again for sharing this high quality content. Your explanations are excellent.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
You're welcome!
@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! 💯
@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!
@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.
@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 9 ай бұрын
@@ManweyVideos i'm stil struggling with that until now.. i cant resolve /refresh problem with unauthorized 401
@RealAshleyBailey
@RealAshleyBailey 10 ай бұрын
I will never understand how people can program code and have it messy like this
@CharlieIoD
@CharlieIoD 7 ай бұрын
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?
@shaeebali8445
@shaeebali8445 Жыл бұрын
Thanks Dave, you’re an awesome teacher. Keep it coming please!
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thanks, will do!
@KazuteruNishi
@KazuteruNishi 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!
@user-fy9zr3pk1o
@user-fy9zr3pk1o Ай бұрын
kzbin.info/www/bejne/nJLZm3ZserB5ndk I can't get why we even need to check whether jwt exist in cookies and if not it will spit 401 error in handleRefreshToken function. The main role of refresh token is that once access token is expired, users will be issued new access token with using refresh token. Therefore, it sounds much reasonable to me that we are going to check if there is access token in cookies, and if not, it will go ahead and check if there is refresh token affiliated with the given authentication information of user, NOT spitting 401 error. Of course, if there is no refresh token too then we will need to cast 401 error.
@digitalclub2220
@digitalclub2220 Жыл бұрын
That DB json file took time and complexity more than using an actual mongodb database.
@danyeun01
@danyeun01 2 ай бұрын
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?
@HelenaCrawford-q6f
@HelenaCrawford-q6f 28 күн бұрын
Clark Michael Thompson Matthew Hall Daniel
@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.
@AntonBAD-u4i
@AntonBAD-u4i 25 күн бұрын
Anderson William Clark George Johnson Linda
@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
@suhas-scrobits
@suhas-scrobits 11 ай бұрын
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
@shineLouisShine
@shineLouisShine 2 жыл бұрын
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 2 жыл бұрын
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 2 жыл бұрын
@@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 2 жыл бұрын
@@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 2 жыл бұрын
​@@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 2 жыл бұрын
(..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..?
@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!
@suvethabalakumar589
@suvethabalakumar589 11 ай бұрын
When I try get request for refresh ,I'm getting unauthorized.
@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! 🙏
@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 :)
@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!
@AprilLeech-x8h
@AprilLeech-x8h 13 күн бұрын
Walker Eric White Karen Miller Linda
@ABUTAHER-wg7gz
@ABUTAHER-wg7gz Жыл бұрын
Hey, How are you doing? if i access and refreshToken both manage by httpOnly cookie accessToken handle like refresh token if Expire access Token server send a new Access Token, do not want store accessToken on any state is it possible? and what will be better you tutorial example or my concept ? please inform me
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
You likely could. Many strategies exist. I wanted to show one of the most common.
@AmitKumar-cp6mx
@AmitKumar-cp6mx 10 ай бұрын
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 8 ай бұрын
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.
@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: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@DenysGarbuz
@DenysGarbuz 10 ай бұрын
qq, how can I ensure that I have http cookie on a client?
@kove5762
@kove5762 Жыл бұрын
43:31 If there's no JWT cookie during logout, shouldn't we send one of 400 codes? Like 401- Unauthorized?
@divyuesharma
@divyuesharma 2 жыл бұрын
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 2 жыл бұрын
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 2 жыл бұрын
@@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. 😊
@mertfromhell
@mertfromhell Ай бұрын
whats the voice change at 36:50 got me shooked
@tjans1979
@tjans1979 8 ай бұрын
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 8 ай бұрын
Apparently this can be handled with axios interceptors?
@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!
@EndLessPain9999
@EndLessPain9999 Жыл бұрын
if someone got issue at 24:05 and got this error message: Error: secretOrPrivateKey must have a value at at Object.module.exports [as sign] I find on google a fix by adding string 'process.env.ACCESS_TOKEN_SECRET' 'process.env.REFRESH_TOKEN_SECRET'
@Peter-wy9sr
@Peter-wy9sr Жыл бұрын
Thanks for the info, but whitelist is not a racist word. Some programmers know so much about code, and so little about reality
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
It's been well over a year so I don't remember exactly what I said, but I don't think I declared it was even though I might have said it feels like it might be. I try to be conscientious for all of my audience. I have been applauded and criticized for the same comment already. No insults necessary.
@mikeysauce393
@mikeysauce393 Жыл бұрын
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. 🌮🌮🌮
@wedadgamalelden
@wedadgamalelden 5 ай бұрын
Thank you for nodejs playlist, Your clear explanations and practical examples made the learning process engaging and effective.
@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.
@MayurChawda-v4e
@MayurChawda-v4e 11 ай бұрын
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
@kimayapanash8998
@kimayapanash8998 Жыл бұрын
secure:true doesnt send cookie to the backend when /refresh is called in my case. Why? and how to fix that?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
In your dev environment, your Node.js code is likely using "http" but when deployed it will use "https". When deployed, you must have secure: true - but it will not work with "http", only "https".
@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 3 ай бұрын
The secure: true flag for dev testing works right using Postman but not using Thunder Client 😊
@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
@sonned9843
@sonned9843 Жыл бұрын
You are the best
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! 🙏
@AsharOran
@AsharOran Жыл бұрын
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: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@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?
@ugurgunes95
@ugurgunes95 2 жыл бұрын
Hi Dave, I'm subscribing you from Turkey and really appreciate for your excellent contents. I just want to ask something. When I create the refreshTokenController and add the logic like you did, I'm registering, and having accessToken from /auth route and when I send a request to /refresh route it returns 401 Unauthorized. I thought maybe I missed something you did so I've downloaded the code from your repository. And I'm facing with the same result. What can I do about that? Thanks a lot!
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
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.
@ugurgunes95
@ugurgunes95 2 жыл бұрын
@@DaveGrayTeachesCode I am using thunder client since I saw it from your videos. In thunder client I couldn’t find how to set secure: true flag.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
@@ugurgunes95 you set secure: true in the code when you create the cookie. I can't remember if ThunderClient lets you edit the cookie after you receive it or not. In this series, I remember noting that I removed secure: true for testing with ThunderClient.
@ugurgunes95
@ugurgunes95 2 жыл бұрын
@@DaveGrayTeachesCode I'm going to have some research about it. If I find something I'll let you know. Thanks again :)
@manuelmartin6132
@manuelmartin6132 3 ай бұрын
The secure: true flag for dev testing works right using Postman but not using Thunder Client 😊
@kirillzlobin7135
@kirillzlobin7135 Жыл бұрын
.env - doesn't have quotes
@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.
@jellyfish1772
@jellyfish1772 3 ай бұрын
Thank you so much!
@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?
@BlenderFrance
@BlenderFrance Жыл бұрын
Hey Dave, thanks for the great tutorial ! I get an undefined req.headers['authorization'] in the verifyJWT middleware. Any hint ?
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
I can only guess about your code. Please compare to my source code for differences. Source code is available at the course resources link in the description.
@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
@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: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@mylastore
@mylastore 2 жыл бұрын
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 2 жыл бұрын
Excellent clarification!
@АбайАлиев-ъ7п
@АбайАлиев-ъ7п 4 ай бұрын
probably the most detailed series on the youtube, although really wish you used ts
@ogt1407gabriel
@ogt1407gabriel Жыл бұрын
hi dave, i get this error when i try to login: blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. and have the allowedorigins and corsoption my code is similar to yours but its with postgresql, and im using redux on the front end on localhost works fine but on the deployed web page this happens
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
When deployed, did you update your allowedOrigins list with the new deployed URL instead of localhost? If so, I recommend going back over your CORS middleware setup as it should handle this. Reference: www.npmjs.com/package/cors
@ogt1407gabriel
@ogt1407gabriel Жыл бұрын
@@DaveGrayTeachesCode yes i have the deployed domain in allowedorigins and all my routes work except the login, i commented the jwt.sign and it works fine somehow it blocks only when i use the jwt.sign, ive looked everywhere and tried everthing i could find but nothing makes it work
@ogt1407gabriel
@ogt1407gabriel Жыл бұрын
@@DaveGrayTeachesCode I found what the problem was, I forgot to add the enviroment token variables to my deployment, LOL
@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.
@rxmanx
@rxmanx Жыл бұрын
41:00
@shineLouisShine
@shineLouisShine 2 жыл бұрын
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 2 жыл бұрын
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.
@kevinspence1771
@kevinspence1771 Жыл бұрын
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 Жыл бұрын
If you set the cookie secure: true, you must use https. Local dev usually just uses http - other comments here on this, too.
@DeepakGupta-hj2dv
@DeepakGupta-hj2dv 3 жыл бұрын
Please make one video Node JS microservices crash course
@DaveGrayTeachesCode
@DaveGrayTeachesCode 3 жыл бұрын
Are their specific microservices you are interested in? A RESTful API like this series has designed powers most microservices. Each microservice then usually has a single function: such as search or other business needs from shipping to payroll.
@DeepakGupta-hj2dv
@DeepakGupta-hj2dv 3 жыл бұрын
@@DaveGrayTeachesCode yes rest api integration microservices series crash course
@DaveGrayTeachesCode
@DaveGrayTeachesCode 3 жыл бұрын
@@DeepakGupta-hj2dv the integration always depends on the service being created, but the code sending and retrieving data from APIs with fetch or Axios always follows the same pattern.
@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: kzbin.info/www/bejne/pHqbgYyQg6unl8U
@jessejohnchiasson4254
@jessejohnchiasson4254 Жыл бұрын
Those JWTs are going to be far to big to be set as a cookie in the browser. >4 kb
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
While a valid concern, this isn't creating tokens with 4096 or more characters. For anyone interested - the concern: stackoverflow.com/questions/60649050/javascript-set-cookie-max-size-is-exceeded-due-to-a-large-jwt-token I'd suggest trying out the code, logging the tokens to the console - or just watch me do it in the video. It does work.
@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
@learner8084
@learner8084 Жыл бұрын
This is a very valuable video for me. I've been trying to understand how the aT and rT works. Thanks very much
@benvingarten3674
@benvingarten3674 7 ай бұрын
In 38:55 when i hit send for the /refresh route i get a response of "unauthorizd". I tried logging the request.cookies.jwt (in the handleRefreshToken) and its undefined. For some reason the cookie is not automatically sent on the request. Moreover when i use the /auth route i do see the accessToken and the cookie (with the refresh token in it) what could be the problem?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 7 ай бұрын
Sounds like you are not sending the cookie with the token to the refresh route. You don't describe how you are trying to send it. Fetch has a credentials option. Axios has withCredentials. Maybe you need to set that.
@benvingarten3674
@benvingarten3674 7 ай бұрын
@@DaveGrayTeachesCode thank you for the respond. You said we don't need to send something in the body or auth in the /refresh because the cookie is sent in every subsequent request of the user. In my case after I go for /login I can see in the response the access token and the cookie. But then when I go for /refresh I'm unauthorized because the request.cookies is undefined, so it's send an error. I overcame this adding the cookie inside the /refresh header, but I don't understand why it doesn't happen automatically like in your code, which btw is exactly like mine.
@nurlanshukurov3864
@nurlanshukurov3864 7 ай бұрын
hi, i got the same error, did you fix it? also in verifyJWT file when we check req.headers["authorization"] i got undefined. is this happen to you too?
@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: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@mahendranath2504
@mahendranath2504 2 жыл бұрын
@@DaveGrayTeachesCode thank you so much 😊👍🙌🏻👏🤝
@shineLouisShine
@shineLouisShine 2 жыл бұрын
Thank you very much. 58:09 - I've checked it : By adding "secure: true" - Refreshing the access token is getting responded with: "401 Unauthorized". Once you delete "secure: true" from authController's res.cookie - Refresh works properly. (And the access token is refreshing with every call to "GET refesh". Do "res.cookie(secure: true)" and refreshing (access token) call- contradict each other?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
They do not contradict each other. secure: true means the URLs must start with https - but in our development environment, our URL starts with http - not https. That is why you must remove secure: true in development.
@ali-celebi
@ali-celebi Жыл бұрын
Hey Dave! How is JWT access token invalidated following user logoff? I can see that refresh token is removed but JWT access token remains valid for some time.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
JWT tokens are often used in a stateless manner, and that is to say, they are not tracked at all but just allowed to expire. I went ahead and tracked refresh tokens in this series so I could later talk about token re-use and rotation, but it is not necessary in many instances. The access tokens should expire in a relatively short time as discussed in the video.
@regilearn2138
@regilearn2138 Жыл бұрын
Hi Dave I have did the sam thing but in 39:28 i didnot get any access token,it shows unauthorized,pls help
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
All I can suggest is to go back over it and find the difference as there must be one. Remember my source code examples are linked in the description, too.
@regilearn2138
@regilearn2138 Жыл бұрын
@@DaveGrayTeachesCode Thank you Dave.
@m_jdm357
@m_jdm357 Жыл бұрын
Good, gooood.
@kiplaharts5643
@kiplaharts5643 11 ай бұрын
Thanks teacher Dave for making this api totorial availabe,
@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.
@coolsuhaib
@coolsuhaib 2 жыл бұрын
i have few questions 1 - why did you use req.user = decode.username at 21:24 2- can you provide the front end code please if possible everything else was good but took long to understand
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
1) We use the jwt.verify method to decode the content inside of the token. One part of that content is the username. We can access it by referring to decoded.username. All of the content is in the decoded object. 2) There is no specific frontend code here. This is a separate backend REST API. One or more frontend applications could access it by making requests.
10 ай бұрын
Again great video. Thank you very much Dave.
@filipdoescode
@filipdoescode 2 жыл бұрын
Weird, got this message: It seems that the size of the like button requested is not available. Please contact KZbin Support for a bigger like button.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
😂 Thank you!
@josephogodja
@josephogodja 2 жыл бұрын
Hello, thanks for the video. But i got an issue wiht the cookies generated. I can't retrieve it from the handleRefresh and logout.
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
There is a link to the course resources (including source code) in the description. I suggest comparing your code to mine to find the differences.
@VinceKully
@VinceKully Жыл бұрын
Hey Dave, thx for this video, it was very informative. I was having issues w/ the JWT middleware causing CORS issues. Turned out when you call the api from the browser (through a react app, for example), it sends 2 requests: an OPTIONS request, followed by the request your front end asked for (GET, POST, etc). In order to fix it, I added a line at the top of my verifyJWT middleware function that returned next() if the req.method was OPTIONS. If anyone else has this issue, hopefully this comment will help them.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Check your CORS middleware and how it is configured. It should be before most everything else in your server and should return the OPTIONS requests well before they get to the verifyJWT middleware.
@VinceKully
@VinceKully Жыл бұрын
​@@DaveGrayTeachesCode I ended up adding an app.options call to take care of it. I must have missed that part of your node tutorial, since I didn't watch the whole thing. Thanks
@anoopthomas2746
@anoopthomas2746 2 жыл бұрын
And bro why should we need access token and refresh token ..why don't we use refresh token for the Authorization...
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
This video should explain the concept. It may help to read it somewhere else like this Auth0 article: auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/
@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
@Elyuli-f3c
@Elyuli-f3c Жыл бұрын
Excellent tutorial. If you could share the frontend form please.
@DaveGrayTeachesCode
@DaveGrayTeachesCode Жыл бұрын
Thank you! You want this playlist: kzbin.info/aero/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd
@zineddinelouzani7069
@zineddinelouzani7069 3 жыл бұрын
Great Explanation 😊
@DaveGrayTeachesCode
@DaveGrayTeachesCode 3 жыл бұрын
Glad you liked it!
@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.
@aya2222
@aya2222 2 жыл бұрын
Thank you for the JWT tutorial, it's very helpful!! I have a question. In logoutController.js, res.clearCookie('jwt', {httpOnly: true}) is used twice, for condition "if(!foundUser)" and for no condition. Is it problem if I just delete res.clearCookie('jwt', {httpOnly: true}) for condition "if(!foundUser)" because res.clearCookie('jwt', {httpOnly: true}) is applied anyway?
@DaveGrayTeachesCode
@DaveGrayTeachesCode 2 жыл бұрын
No, the conditional statement has a return inside. The 2nd res.clearCookie you see will not be reached in that case.
@aya2222
@aya2222 2 жыл бұрын
@@DaveGrayTeachesCode Ah!! I misunderstood super basic stuff.. Thank you so much!!
@DeepakGupta-hj2dv
@DeepakGupta-hj2dv 3 жыл бұрын
Great explanation Dave ..complete this series? ??
@DaveGrayTeachesCode
@DaveGrayTeachesCode 3 жыл бұрын
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 3 жыл бұрын
Please start new new project mern stack with react with redux
@DaveGrayTeachesCode
@DaveGrayTeachesCode 3 жыл бұрын
@@DeepakGupta-hj2dv yes, I will be creating projects with this stack.
@yashsharma6112
@yashsharma6112 Жыл бұрын
You are awesome. Great videos with a rich content.
@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: kzbin.info/www/bejne/jJ60Z5d-q9N-f68
Session Vs JWT: The Differences You May Not Know!
7:00
ByteByteGo
Рет қаралды 166 М.
Nastya and balloon challenge
00:23
Nastya
Рет қаралды 69 МЛН
Миллионер | 1 - серия
34:31
Million Show
Рет қаралды 2,1 МЛН
The selfish The Joker was taught a lesson by Officer Rabbit. #funny #supersiblings
00:12
Electric Flying Bird with Hanging Wire Automatic for Ceiling Parrot
00:15
JWT Authentication Tutorial - Node.js
27:36
Web Dev Simplified
Рет қаралды 1 МЛН
What Is JWT and Why Should You Use JWT
14:53
Web Dev Simplified
Рет қаралды 1,2 МЛН
Make Money from your API Tutorial
13:10
Fireship
Рет қаралды 877 М.
Intro to MongoDB and Mongoose | Node.js Tutorials for Beginners
17:06
Node.js API Authentication With JWT
23:01
Traversy Media
Рет қаралды 557 М.
Nastya and balloon challenge
00:23
Nastya
Рет қаралды 69 МЛН