NestJs JWT - Access Tokens & Refresh Tokens - Ultimate Guide

Поделиться
HTML-код
  • Опубликовано: 10 сен 2024

Комментарии • 309

  • @omidr666
    @omidr666 2 года назад +40

    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
      @aadispare3673 2 года назад +2

      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
      @big-jo89 2 года назад

      @@aadispare3673
      checkout this tutorial by Dave Gray ruclips.net/video/4TtAGhr61VI/видео.html

    • @qunther
      @qunther Год назад +2

      @@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
      @aadispare3673 Год назад

      @@qunther makes sense mate. Thank you 😊

    • @ahmadnabil5779
      @ahmadnabil5779 10 месяцев назад

      Cool!

  • @scottamolinari
    @scottamolinari 2 года назад +19

    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
      @CodeWithVlad  2 года назад +13

      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
      @ahmadnabil5779 10 месяцев назад

      Can the mobile client access the cookie if the refresh token is stored in cookie with httponly?

    • @scottamolinari
      @scottamolinari 10 месяцев назад

      @@ahmadnabil5779 No. That's the reason why there are httponly cookies, so clients can't mess with them.

  • @intermix1297
    @intermix1297 Год назад +2

    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

  • @ToshisanMotonaka
    @ToshisanMotonaka 2 года назад +44

    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
      @CodeWithVlad  2 года назад +2

      Thanks a lot! It makes my day :)

    • @CodeWithVlad
      @CodeWithVlad  2 года назад +2

      Please don't forget to use argon2 instead of bcrypt (check the pinned comment)

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

  • @KetanAjani93
    @KetanAjani93 2 года назад +6

    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.

  • @es7729
    @es7729 2 месяца назад

    You came here and wondering is it worth watching this video? Absolutely!
    Thanks, Vlad!

  • @renends7615
    @renends7615 2 года назад +16

    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!

  • @aleksandrpetrov3938
    @aleksandrpetrov3938 11 месяцев назад +1

    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

  • @diatm1506
    @diatm1506 2 года назад +1

    Thank you so much I finally searched all over the Internet

  • @octavenkurunziza8680
    @octavenkurunziza8680 4 месяца назад

    me recognizing the errors before vlad does proves i m getting better😂 thanks for the explanation tho i needed this

  • @Jeff_Leon
    @Jeff_Leon Месяц назад

    Massive thanks for this wonderful video. You saved me days! Vlad, I wish you to thrive in your career :)

  • @htmlandcsstutorial820
    @htmlandcsstutorial820 Год назад +1

    Vlad is the best tutor for me

  • @ebratz
    @ebratz 2 года назад +7

    What a masterclass on the subject! Thank you really much for publishing this video!

  • @victordepta4069
    @victordepta4069 2 года назад +7

    Great tutorials you make. Congrats mate! Please covers specs and integration testing.

    • @CodeWithVlad
      @CodeWithVlad  2 года назад

      All planned :)

    • @CodeWithVlad
      @CodeWithVlad  2 года назад +2

      The video on integration testing will be released 9am today :)

  • @motziesel
    @motziesel 2 года назад +2

    Thank you very much for showing the context and how it is actually done in a real project :)

  • @saeeduchiha5537
    @saeeduchiha5537 7 месяцев назад

    one of the best videos in authentication using refresh tokens

  • @christophermaisch
    @christophermaisch 2 года назад +10

    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! 👏👏👏

  • @spellsaif
    @spellsaif Год назад +2

    You are awesome. You are making me to love nestjs more. Thank you sensei 😊

  • @AbdulHanan-ci3se
    @AbdulHanan-ci3se Год назад

    This is amazing tutorial 🙌,
    I remember before watching the video I had implement Auth-JWT and it took 3 days to understand and implement.

  • @Teddyrobinson
    @Teddyrobinson 7 месяцев назад

    Can't believe I made it all the way to the end!! Thanks so much.

  • @thesunnatillo
    @thesunnatillo Месяц назад

    Vlad aka darslariz juda zo'r (from Uzbekistan)

  • @PaulPariat
    @PaulPariat 9 месяцев назад

    Thanks for this wonderful tutorial! It was great understanding refresh tokens along with Nestjs at the same time

  • @v-olyunin
    @v-olyunin 2 года назад +3

    You can replace 60 * 60 * 24 * 7 in expiresIn with string '7d'/'15m'/'1w' etc...

  • @itsgoubie
    @itsgoubie 2 года назад +1

    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

  • @ivandariogye
    @ivandariogye 11 месяцев назад

    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.

  • @tarifulislamfahim9348
    @tarifulislamfahim9348 8 месяцев назад

    Awesome. i followed this exciting tutorial to build authentication for my own project. Thank you

  • @GodfatherOfKcontent
    @GodfatherOfKcontent 2 года назад

    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.

  • @donluc007
    @donluc007 10 месяцев назад

    wow - well done Vlad, one of the most comprehensive tutorials / real course, thanks a bunch for your effort and for sharing this knowledge!

  • @klik24
    @klik24 2 года назад +1

    Wish I found your video few days back. Great explanation, one of the best I heard & actually understood. Many thanks Vlad.

  • @Yoggan0
    @Yoggan0 2 года назад

    you are a GOD i watched so many tutorials and yours is the only one that actually works, 🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @imthedaniels
    @imthedaniels Год назад

    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 RUclips 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!

  • @jojog2624
    @jojog2624 2 года назад +3

    Great tutorials! Explained clearly with a very practical project! Thanks a lot for your sharing!
    Looking forward to your new videos about anything :D

  • @mfurkankaya
    @mfurkankaya Год назад

    I think this is the best tutorial for auth flow. Thanks!

  • @louislecouturier
    @louislecouturier Год назад

    Man... This is actually one of the best tutorial I've ever watched ! You're a really good teacher, thanks a lot !

  • @jeandedieuiradukunda6079
    @jeandedieuiradukunda6079 8 дней назад

    Thank you, it was an incredible tutorial

  • @mohammadalathamena
    @mohammadalathamena 2 года назад

    this is awesome , this is best tutorial i have seen for jwt authentication on youtube

  • @onuralkan190
    @onuralkan190 8 месяцев назад

    Best learning content and teacher i ever seen!

  • @healsy_ru
    @healsy_ru 2 года назад +1

    Прекрасное видео! Видно, что в проекте позже был использован Аргон, что тоже круто) Надеюсь увидеть в будущем более продвинутую реализацию, в том числе с функционалом активации аккаунта по почтовому ящику. Спасибо за такой ценный контент!

  • @ali.muhsin
    @ali.muhsin Год назад

    Just helped me do the first task in my internship!
    Thxxxx

  • @iPururin
    @iPururin 2 года назад +4

    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
      @CodeWithVlad  2 года назад +1

      I'm glad you loved it! Please don't forget to use argon2 instead of bcrypt (check the pinned comment)

  • @codernerd7076
    @codernerd7076 2 года назад

    Thanks this is the type of quality tutorials I want to see on RUclips!

  • @ragsbigfella
    @ragsbigfella 6 месяцев назад

    Vlad, loved your video on NextJS on Free code camp. Thank you. Really appreciate it.

  • @josephhenshaw4912
    @josephhenshaw4912 Год назад

    I just want to say this is a blessing, thank you, excellent

  •  2 года назад

    This has been by far the best tutorial I have seen about authentication in nest with jwt, congratulations!

  • @ktoscos4546
    @ktoscos4546 8 месяцев назад

    It was good Christmas with this tutorial , thanks

  • @ugurcanbas3821
    @ugurcanbas3821 Год назад

    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.

  • @user-cf3id5zz9v
    @user-cf3id5zz9v Год назад

    This tutorial is more then excellent.

  • @nickchauhan
    @nickchauhan 2 года назад

    Best video I've seen so far for the JWT implementation in Nest Js. Thanks Vlad.
    Subscribed :)

  • @abdulkhaliq6857
    @abdulkhaliq6857 2 года назад

    Amazing Man! I just followed and implemented AT & RT. Yuhuuu....Thanks...!

  • @akerenkater8437
    @akerenkater8437 2 года назад

    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
      @CodeWithVlad  2 года назад +2

      Aaah microservices, I will get to them soon. Need to first provide content on sessions and graphql. :) Thank you Akeren, much appreciated!

  • @joaquinnader
    @joaquinnader 2 года назад +1

    this is pure gold! Thank you so much

  • @outer-space-coding
    @outer-space-coding Год назад

    Спасибо, Влад! Супер комплексный подход! В самом начале долго не мог понять, так какой же стандарт жизни access токена, 15 или 50 минут. Я же дилетант, обычно делал пять часов. ) Просто обычно в слове "fifteen" ударение на последний слог, а слышалось как будто "fifty" с ударением на первый слог. Еще раз спасибо за видео!

    • @tray174
      @tray174 Год назад

      Забавно, я тоже об этом думал, но не стал писать, думал непринципиально, но оказывается кого-то это даже путает)

  • @AleHacho
    @AleHacho 6 месяцев назад

    Thank you, very nice tutorial, i'll try to implement this with redis too.
    Sorry for my english and thank you again.

  • @StevenValencia1998
    @StevenValencia1998 3 месяца назад +2

    But in this scenario, when an access token expires and we call the refresh endpoint, we're updating both tokens. Given this situation, the refresh token expiration wouldn't make sense, right?

  • @bayoumi-tech
    @bayoumi-tech Год назад

    This tutorial is excellent.
    Thank you very much

  • @robertofloresrosas1855
    @robertofloresrosas1855 2 года назад

    Excelente, es la mejor explicación que he encontrado. Te lo agradezo mucho

  • @ayanokojikiyotaka1923
    @ayanokojikiyotaka1923 Год назад

    thanks for tutorial, you explained very well and easily help me a lot.

  • @baophunggia9835
    @baophunggia9835 2 года назад

    Thank you so much bro. This is very helpful for me and everyone

  • @truelife9859
    @truelife9859 2 года назад

    Thank you for Excellent tutorial. Yes of course I like to understand testing techniques too.
    Thanks

    • @CodeWithVlad
      @CodeWithVlad  2 года назад +1

      I'm glad you loved it! Please don't forget to use argon2 instead of bcrypt (check the pinned comment)

  • @ramalingamgurunathan1085
    @ramalingamgurunathan1085 2 года назад

    Excellent tutorial, Its very helpful. Thank you very much Boss

  • @adrianlineweaver4725
    @adrianlineweaver4725 2 года назад +1

    was looking for something like this!

  • @philstarcrypto6994
    @philstarcrypto6994 2 года назад

    Vlad keep going! Amazing stuff

  • @nldcarbonfiber206
    @nldcarbonfiber206 2 года назад

    You're amazing dude, I really appreciate it. You helped me out so much!

  • @OlehBiblyi
    @OlehBiblyi 2 года назад

    WOW, very interesting, please, keep going with videos like this!

  • @user-jd7ub3tq2b
    @user-jd7ub3tq2b Год назад

    Super detailed video, thanks. It would be cool if you showed how to add Google authorization to this

  • @eduardoaosorio
    @eduardoaosorio Год назад +1

    Hey Vlad, great video! However, I noticed a downside to this approach, if a user signs in in another app/device his first refresh token will stop working, since the hashed refresh token in the DB will be updated at the moment of the second sign in. Lets say you have a web app and a mobile app. A user signs in in the web app and then proceeds to sign in in the mobile app. The moment the user signs in the mobile app his refresh token for the web app will be replaced in the DB with the mobile app's refresh token, later at the moment of requesting new tokens from the web app this will fail and he will have to log in again, which will then cause the same issue but in the mobile app. In other words, a user won't be able to maintain 2 "sessions" in different devices/apps.

    • @kyborq
      @kyborq 8 месяцев назад +1

      Yeah, so you need to store tokens separated from users table

  • @namangarg3933
    @namangarg3933 2 года назад

    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.

  • @SyedZainUlHasan
    @SyedZainUlHasan 2 года назад

    Very nice video. But get very complicated after some time. :P Thank you Vlad

  • @AT-mx3bx
    @AT-mx3bx 2 года назад

    Amazing tutorial, so glad I found this

  • @sirlionellord
    @sirlionellord 5 месяцев назад

    Thanks a lot. Very nice 🔥🔥

  • @jaesunghong6367
    @jaesunghong6367 2 года назад +1

    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
      @CodeWithVlad  2 года назад +1

      Hey! Thank you for your comment and suggestion. This topic is definitely planned! For deployment I am using aws and hetzner cloud

    • @Tobias-mz7nm
      @Tobias-mz7nm 2 года назад

      @@CodeWithVlad im waiting :D

  • @WizraiderRD
    @WizraiderRD 2 года назад

    Muchas gracias hermano, bendiciones. He aprendído mucho y quiero que sepas que me estouy dedicando al back-end.

  • @user-yq4gv3dv2e
    @user-yq4gv3dv2e 2 года назад

    Thank you so much! Very useful video

  • @ademhatay
    @ademhatay Месяц назад

    Wow, that's great.

  • @tray174
    @tray174 Год назад

    Кекаю с каждого "МЫТАДАТА" (metadata) произнесенного на протяжение видео)) Но да, за гайд респект, очень подробно всё и это прекрасно)

  • @hiranpeiris3210
    @hiranpeiris3210 2 года назад

    Thank you. I have learned a lot.

  • @Zygfryd_z_Toussaint
    @Zygfryd_z_Toussaint Год назад +19

    Why is everyone storing refresh token as a column in users table? That make no sense, because users can be logged in only on one device with refresh token. In my opinion better is to store both tokens as http only cookies with refresh token saved only with "/refresh" path and stored in Redis with key like "refresh:userId:jti". You can then store some device informations in the payload to let the end user list all refresh tokens with their devices and ability to instantly revoke

    • @Zygfryd_z_Toussaint
      @Zygfryd_z_Toussaint Год назад +3

      But anyway it is the best video covering this topic I've ever seen

    • @blender_wiki
      @blender_wiki Год назад

      Cookies are to avoid like hell on any manner in any modern app design

    • @cedricmataso2446
      @cedricmataso2446 Год назад +1

      Bro make a pull request. This would help

  • @maikeontime
    @maikeontime 2 года назад

    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?

  • @ralgit
    @ralgit 2 года назад

    I was looking for this, thanks! 🙌

  • @fuxiaochen
    @fuxiaochen Год назад

    Super detailed and useful examples !❤

  • @danilmakarov2726
    @danilmakarov2726 8 месяцев назад

    Thanks, great tutorial!

  • @mayoniaise5169
    @mayoniaise5169 2 года назад

    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
      @nobytes2 2 года назад

      At that point you might as well use sessions.

    • @mayoniaise5169
      @mayoniaise5169 2 года назад

      @@nobytes2 if the client handle it ;)

  • @ceetatsumi1449
    @ceetatsumi1449 2 года назад

    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 ?

  • @ibadshaikh2215
    @ibadshaikh2215 5 месяцев назад

    Awesome video.

  • @ilyagrebenyuk3656
    @ilyagrebenyuk3656 Год назад +1

    Hi guys, I followed the guide completely, but I used argon instead of bcrypt and I have the following problem: when I take a refresh token and refresh it, then I can refresh it again with the old refresh token. Thus, if an attacker takes possession of the refresh token, then he can always receive an access token, this is bad. Does the bcrypt solution have the same problem?

  • @CodeWithVlad
    @CodeWithVlad  2 года назад +13

    Merry Christmas everyone!
    After some tests, I realized that bcrypt is not a good option for that case since it can only compare passwords that are smaller than 72 bytes!
    The JWT we hash is bigger than 72 bytes, hence the compare function will always return true! 😐
    Please use argon2 instead of bcrypt! www.npmjs.com/package/argon2
    Also, I have a more recent video on authentication where I don't recommend using JWT as a session token and use session instead: ruclips.net/video/8haNjnq26K4/видео.html

    • @rluvaton
      @rluvaton 2 года назад

      If I understand your comment correctly it sounded like you say that the user password is stored in the JWT.
      This is a big NO! as JWT token can be parsed by anyone and therefore get the password that you stored in it

    • @CodeWithVlad
      @CodeWithVlad  2 года назад +2

      @@rluvaton No it does not store the user password. I was talking about the fact that the library "bcrypt" is used for storing passwords (which are usually less that 72 bytes long). So the verify function does not work correctly with longer values.

    • @NicolasRuizX
      @NicolasRuizX 2 года назад

      thank you! I was going crazy because the refresh token was always returning true

    • @pawel_890
      @pawel_890 2 года назад

      RefreshToken should be some hash, but not JWT :)

  • @therock6391
    @therock6391 Год назад

    Thank you It is very helpful

  • @andresfcuellarc
    @andresfcuellarc Год назад

    Excellent thanks very mucsh

  • @muchamadfaiz2391
    @muchamadfaiz2391 11 месяцев назад

    00:00:00 Introduction
    00:19:23 Database migration

  • @user-kd5sv7mc1k
    @user-kd5sv7mc1k Год назад

    you are the best pro, thank you :)

  • @oreyon9514
    @oreyon9514 Месяц назад

    Hi vlad, how you handle or invalidated access token after logout? I have try overwrite the access token and refresh token to be expiring after a few second but it seems like does not have effect on it.

  • @thelanelim92
    @thelanelim92 2 года назад

    Great video Vlad 👌🏻👌🏻👌🏻👌🏻👌🏻

  • @fasttocode
    @fasttocode 2 года назад

    You are awesome!, Thank you.

  • @dev.caixeiroviajante
    @dev.caixeiroviajante Год назад

    Vlad, thanks for the great and awesome content.
    Now, which theme are u using ? haha

  • @atvu2245
    @atvu2245 2 года назад

    Excellent tutorial !👏👏

  • @justinnoor4915
    @justinnoor4915 2 года назад

    Excellent video

  • @VizivikRu
    @VizivikRu 2 года назад

    Thanks, a lot!!!

  • @ChrisJaydenBeats
    @ChrisJaydenBeats 2 года назад

    Damn! You nailed it 🙏

  • @bartoszpierdolny6978
    @bartoszpierdolny6978 2 года назад +3

    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?

  • @husnulaman
    @husnulaman 2 года назад

    Great tutorial 🔥👏 please do one with sessions as well

    • @CodeWithVlad
      @CodeWithVlad  2 года назад +1

      A lot of people asking for sessions, seem like I don't have the choice than to make a video about that :)