NestJs JWT - Access Tokens & Refresh Tokens - Ultimate Guide
In this video, I will be building a complete authentication module with logout and refresh functionality. I will also show how you can use access tokens and refresh tokens with passport js and nestJs.
If you love this video consider leaving me a like to help with the youtube algorithm and subscribing if you haven't.
Github repo of the project: github.com/vladwulf/nestjs-jwts
00:00 NestJs Jwt Authentication Intro
08:58 Prisma and Docker setup
19:35 Prisma service
23:00 Auth module
39:50 Setting up Passport strategies
47:00 NestJs Jwt Module
54:00 Updating refresh token hash
1:02:40 Logout function
1:06:00 Jwt Guards
1:12:00 Refresh tokens function
1:19:00 Get Current User decorator
1:29:00 Access token and Refresh token guards
1:30:00 Access token guard can activate
IMPORTANT: Please use argon for hashing and verifying refresh tokens (www.npmjs.com/package/argon2). Bcrypt is only good for short passwords (less than 74 bytes). Since our refresh token is a JWT, it will be longer than 74 bytes, so our bcrypt compare function might return true when it should not!
Пікірлер: 303
Thank you for the tutotial, it's a good one. I just wanted to make a few points. From the security standpoint, the good practice is to have JWT in memory or basically sending through http context and save refresh token in an http only cookie so when a user leaves their browser and comes back again, the application can uses the refresh token to issue a new access token. But, by using your approach, when a user refreshes their browser or closes it they lose both access and refresh tokens and they have to sign in again in order to access the protected area of the application. In SPA applications you use a refresh token in order to issue an access token again after its expiration, so we need to keep it somewhere safe to use it again, otherwise it is pointless to use it. On top of that, when you only use one refresh token in your user's entity and every time you replace it with a new one, then users will not be able to have their multiple devices logged in, because whenever they logs in in each device,then the previous refresh token they used in another device will be replaced with a new one and their another device will be no longer logged in. So we need a user entity that has one to many relationship with a refresh token entity. You can also read more about the security recommendations for access and refresh tokens from the link below if you are interested: dev.to/cotter/localstorage-vs-cookies-all-you-need-to-know-about-storing-jwt-tokens-securely-in-the-front-end-15id
@aadispare3673
Жыл бұрын
That's a very clear explanation. Thank you so much. Although I just have one naive question... From SPAs, we always send access tokens in headers... How do we know when to send the refresh token to generate new tokens? I mean when the access token is expired it will send an unauthorised (forbidden) exception or something of that sort. Then how do we send the refresh token? Any working example code would be really helpful. Thank you
@big-jo89
Жыл бұрын
@@aadispare3673 checkout this tutorial by Dave Gray kzread.info/dash/bejne/Zoioo6mhopmXhqw.html
@qunther
Жыл бұрын
@@aadispare3673 Late answer here, but actually when you hit a protected route, if the access token has expired you will get an unauthorized exception, so you must catch this exception by hitting the refresh tokens route if the refresh token is not expired too, then try to hit the first route again
@aadispare3673
Жыл бұрын
@@qunther makes sense mate. Thank you 😊
@ahmadnabil5779
8 ай бұрын
Cool!
Wish I found your video few days back. Great explanation, one of the best I heard & actually understood. Many thanks Vlad.
Great tutorials! Explained clearly with a very practical project! Thanks a lot for your sharing! Looking forward to your new videos about anything :D
This tutorial is excellent. A great teacher, who makes us go deeper into the content through knowledge, good humor, sincerity (because there were no cuts in the moments of code error) and many tips to evolve as developers. Thanks!
What a masterclass on the subject! Thank you really much for publishing this video!
This is elegant, Vlad. You inductively demystify the abstract concepts and made them look simpler for digestion. I look forward to learning the Microservice with NestJs from you. Thanks, Man! 🥰
@CodeWithVlad
2 жыл бұрын
Aaah microservices, I will get to them soon. Need to first provide content on sessions and graphql. :) Thank you Akeren, much appreciated!
wow - well done Vlad, one of the most comprehensive tutorials / real course, thanks a bunch for your effort and for sharing this knowledge!
Man... This is actually one of the best tutorial I've ever watched ! You're a really good teacher, thanks a lot !
This is excellent content 💯. The flow of learning concepts and writing code hits the mark. Major kudos for covering typescript safety, especially for creating custom decorators and explaining the public guards. Thank you, this was an easy subscription from me.
@CodeWithVlad
2 жыл бұрын
I'm glad you loved it! Please don't forget to use argon2 instead of bcrypt (check the pinned comment)
Vlad, thank you again. You are really putting a lot of effort into these videos dude and we can see it in your how you are able to tie multiple concepts together in a way that logically flows so well! You have taught us in hours what it takes some years to understand so thank you for literally giving me extra life points! 👏👏👏
@CodeWithVlad
2 жыл бұрын
Thank you a lot Christopher!
To learn NestJS Authentication I have seen many videos and I got confuse about JWT but with your video I am pretty clear and the way you explain everything is awesome. Thanks.
Best video I've seen so far for the JWT implementation in Nest Js. Thanks Vlad. Subscribed :)
Thank you very much for showing the context and how it is actually done in a real project :)
Прекрасное видео! Видно, что в проекте позже был использован Аргон, что тоже круто) Надеюсь увидеть в будущем более продвинутую реализацию, в том числе с функционалом активации аккаунта по почтовому ящику. Спасибо за такой ценный контент!
I was trying to find a tutorial for many days that would explain the reason for each thing and not just give me the code. Your tutorial is one of the best I've seen on KZread and I'm surprised it's free, congratulations on something so amazing, you earned a subscriber. I hope you can launch courses, I will buy for sure. Hugs from Brazil!
This is amazing tutorial 🙌, I remember before watching the video I had implement Auth-JWT and it took 3 days to understand and implement.
Hey. Nice video. Some points of interest. 1. @Injectable tells Nest to reflect on the constructor and see if there are dependencies it needs to inject into it. If there are no dependencies to inject, you don't need the decorator. 2. You can store tokens in local storage on the client, however they are open to an XSS attack and with 7 days (for the refresh token), a lot of damage can be done. I'd suggest storing the refresh token in an http only cookie. This avoids XSS attacks, as attackers won't be able to get access to the cookie. You should also add the "/refresh" path to the cookie too, so the cookie is only sent on requests made to the "/refresh" endpoint.
@CodeWithVlad
2 жыл бұрын
Thank you a lot for this comment! 1. Yes 100% :) 2. Excellent suggestion, I had a couple of discussions on reddit and we agreed that what you suggest would be the best solution. I will prepare a video on the subject
@ahmadnabil5779
8 ай бұрын
Can the mobile client access the cookie if the refresh token is stored in cookie with httponly?
@scottamolinari
8 ай бұрын
@@ahmadnabil5779 No. That's the reason why there are httponly cookies, so clients can't mess with them.
Not sure if the 15mins delay logout w/ refresh token hash is from who's idea. that's cunningly brilliant. one of the finest JWT tutorials ever. keep up the good work. i totally appreciate your time and effort.
That was awesome! I'm new with NestJs and started to create my own demos. I've learned almost everything from you. Thank you so much for sharing that much information.
@CodeWithVlad
Жыл бұрын
Glad to help!
This is the greatest guide to understanding JWT + refresh! Thank you so much, it really helped me really nail down this concept and practice!
@CodeWithVlad
2 жыл бұрын
Thanks a lot! It makes my day :)
@CodeWithVlad
2 жыл бұрын
Please don't forget to use argon2 instead of bcrypt (check the pinned comment)
@ToshisanMotonaka
2 жыл бұрын
@@CodeWithVlad I have a question; while I understand the concept and have some practical experience, one thing I'm having difficulty with is determining the best method to implement this with some frontend code.
Thanks for this wonderful tutorial! It was great understanding refresh tokens along with Nestjs at the same time
You are awesome. You are making me to love nestjs more. Thank you sensei 😊
This has been by far the best tutorial I have seen about authentication in nest with jwt, congratulations!
@CodeWithVlad
2 жыл бұрын
Thank you! 😊
Thanks this is the type of quality tutorials I want to see on KZread!
@CodeWithVlad
2 жыл бұрын
More to come!
This is such an amazing video. Glad I stumbled across this. Subscribed. Would be going through the other videos on your channel. And, eager to learn more from you. Thank you so much.
Can't believe I made it all the way to the end!! Thanks so much.
one of the best videos in authentication using refresh tokens
Not long and not tedious. That's what tutroial should be. You get the whole idea in one video and then just keep on your coding. Thank you for the tutorial
Awesome. i followed this exciting tutorial to build authentication for my own project. Thank you
You're amazing dude, I really appreciate it. You helped me out so much!
Excelente, es la mejor explicación que he encontrado. Te lo agradezo mucho
this is awesome , this is best tutorial i have seen for jwt authentication on youtube
It was good Christmas with this tutorial , thanks
Thank you so much I finally searched all over the Internet
@CodeWithVlad
2 жыл бұрын
Tnak you! :D
You're the best! All the things that I know in NestJS are thank to you and your videos, you explain it so well! Now I was wondering, can you make a video on Redis and sessions too?
Спасибо, Влад! Супер комплексный подход! В самом начале долго не мог понять, так какой же стандарт жизни access токена, 15 или 50 минут. Я же дилетант, обычно делал пять часов. ) Просто обычно в слове "fifteen" ударение на последний слог, а слышалось как будто "fifty" с ударением на первый слог. Еще раз спасибо за видео!
@tray174
Жыл бұрын
Забавно, я тоже об этом думал, но не стал писать, думал непринципиально, но оказывается кого-то это даже путает)
You have upgraded me big time. Thanks!
You came here and wondering is it worth watching this video? Absolutely! Thanks, Vlad!
I think this is the best tutorial for auth flow. Thanks!
Great tutorials you make. Congrats mate! Please covers specs and integration testing.
@CodeWithVlad
2 жыл бұрын
All planned :)
@CodeWithVlad
2 жыл бұрын
The video on integration testing will be released 9am today :)
Thank you so much bro. This is very helpful for me and everyone
Vlad is the best tutor for me
Excellent tutorial, Its very helpful. Thank you very much Boss
Amazing tutorial, so glad I found this
me recognizing the errors before vlad does proves i m getting better😂 thanks for the explanation tho i needed this
I like that you don't cut out the way you look for bugs in the code. It helps to keep track of the way you think when something goes wrong
Best learning content and teacher i ever seen!
Vlad, loved your video on NextJS on Free code camp. Thank you. Really appreciate it.
I just want to say this is a blessing, thank you, excellent
Vlad keep going! Amazing stuff
Thank you, very nice tutorial, i'll try to implement this with redis too. Sorry for my english and thank you again.
I was looking for this, thanks! 🙌
Thank you for Excellent tutorial. Yes of course I like to understand testing techniques too. Thanks
@CodeWithVlad
2 жыл бұрын
I'm glad you loved it! Please don't forget to use argon2 instead of bcrypt (check the pinned comment)
Just helped me do the first task in my internship! Thxxxx
@CodeWithVlad
Жыл бұрын
Glad to hear that Ali!
thanks for tutorial, you explained very well and easily help me a lot.
Amazing Man! I just followed and implemented AT & RT. Yuhuuu....Thanks...!
This tutorial is excellent. Thank you very much
this is pure gold! Thank you so much
@CodeWithVlad
2 жыл бұрын
Thank you
Thank you so much! Very useful video
Super detailed and useful examples !❤
@CodeWithVlad
Жыл бұрын
Thank you! 😃
Thanks, great tutorial!
Thank you. I have learned a lot.
This tutorial is more then excellent.
WOW, very interesting, please, keep going with videos like this!
@CodeWithVlad
2 жыл бұрын
Thanks, will do!
you are a GOD i watched so many tutorials and yours is the only one that actually works, 🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@CodeWithVlad
2 жыл бұрын
Thank you!
Thanks a lot. Very nice 🔥🔥
Nice tutorial, thanks! Actually it's nice seeing someone experienced mess up a little bit and find the solution on the go, that's how coding really is like.
Excellent tutorial !👏👏
Very nice video. But get very complicated after some time. :P Thank you Vlad
Чел, ты великолепен! Видео очень качественное, зашло Мог бы написать и на английском, но не думаю, что это необходимо)
Great video Vlad 👌🏻👌🏻👌🏻👌🏻👌🏻
Muchas gracias hermano, bendiciones. He aprendído mucho y quiero que sepas que me estouy dedicando al back-end.
i'm following this tutorial using Mongo instead of Postgres and it's even simpler. i don't know if it's more appropriate but it's easier. just a few issues related to migrate and the id field but other than that, very smooth sailing
was looking for something like this!
@CodeWithVlad
2 жыл бұрын
Amazing!
amazing tutorial vlad!
@CodeWithVlad
2 жыл бұрын
Thanks Tim!
Was here for the refresh function part... Ends up watching the whole video ! Thank you for all the tips ! Can you explain why are you using index.ts ?
Awesome video.
Great tutorial 🔥👏 please do one with sessions as well
@CodeWithVlad
2 жыл бұрын
A lot of people asking for sessions, seem like I don't have the choice than to make a video about that :)
Thank you It is very helpful
Excellent video
Good job!
You are awesome!, Thank you.
Subscribed! So nice. :) thank you.
@CodeWithVlad
Жыл бұрын
Thanks for the sub!
Vlad, thanks for the great and awesome content. Now, which theme are u using ? haha
Great video!
Nice one, thanks!
Excellent thanks very mucsh
Damn! You nailed it 🙏
Super detailed video, thanks. It would be cool if you showed how to add Google authorization to this
you are the best pro, thank you :)
I'm so glad that you are using the same tech stacks as me. Nest.js + Prisma is so powerful. Can you make a video about deployment? I'm so curious about what cloud provider you use and how you handle the deployment.
@CodeWithVlad
2 жыл бұрын
Hey! Thank you for your comment and suggestion. This topic is definitely planned! For deployment I am using aws and hetzner cloud
@Tobias-mz7nm
Жыл бұрын
@@CodeWithVlad im waiting :D
Nice video, Vlad! Btw, did you try to use autogenerated prisma DTOs? Do you know how we can validate, cover in documentation (and all that stuff) them by any chance?
Thanks so much!
Awesome tutorial. Thank you so much! Can you please make a tutorial about CICD with NestJs and Prisma.
@CodeWithVlad
2 жыл бұрын
Thank you for the compliment and the suggestion. It’s an interesting topic. I will see if i can cover it in a future video.
You're awesome. Thank for this tutorial. Btw, what do you use autocomplete in command line ?
awesome man !
Кекаю с каждого "МЫТАДАТА" (metadata) произнесенного на протяжение видео)) Но да, за гайд респект, очень подробно всё и это прекрасно)
@CodeWithVlad
Жыл бұрын
haha :)
Hi and thank you for the explanations which really help to understand JWT and refresh. But we really lose the interesting side of stateless because the logic is designed to handle only one login at a time. If you sign from another device, you lose the previous hash... I think it's better to keep a history per user in redis, a hashmap per user containing all the hashes of refresh tokens and a TTL close to that JWT expirations. This allows you to logout by removing the correct hashes in redis and even to log out all devices by removing the complete hashmap.
@nobytes2
2 жыл бұрын
At that point you might as well use sessions.
@mayoniaise5169
2 жыл бұрын
@@nobytes2 if the client handle it ;)
Nice!
Thankss 👏