NestJS Authentication: JWTs, Sessions, logins, and more! | NestJS PassportJS Tutorial

Sdílet
Vložit
  • čas přidán 9. 07. 2024
  • In this video we'll discuss the fundamentals of adding authentication to your NestJS API. We'll talk about utilizing passport to use different types of authentication strategies. Specifically we will try the passport-local strategy as a basic login with username and password example. Next, we'll take a look at potentially using sessions to store user information and persist their login state. Finally we will also take a look at a state-less approach with JSON Web Tokens (JWTs). We'll create our own JWTs and I'll show you how you can use that to protect your API routes!
    00:00 - Intro
    03:35 - Initial routes
    04:41 - UsersService
    07:50 - AuthService
    10:40 - Implementing passport-local strategy (username/password login)
    18:08 - AuthGuards
    23:25 - Summary of local login flow
    29:02 - Guard to check if user is authenticated
    31:41 - Setting up sessions
    40:37 - Summary of login with sessions flow
    44:25 - Setting up JWT strategy, signing and validating
    1:00:25 - Summary of JWT strategy flow
    1:04:22 - Conclusion
    1:05:20 - Outro

Komentáře • 420

  • @mariusespejo
    @mariusespejo  Před 2 lety +46

    Note: a lot of people are getting the error “request.isAuthenticated is not a function”. Please note that I explicitly mentioned in the video that it will not work until you properly setup sessions. If you run into that error, KEEP watching! The problem will resolve itself once you have the full setup, don’t stop at the point of error. If you watch the rest of the video and still have this problem, double check that you properly configured and registered your strategies and guards exactly as shown in the video.

    • @David-rz4vc
      @David-rz4vc Před 2 lety

      in main.ts: below fix it for me
      app.use(passport.initialize());
      app.use(passport.session());

    • @yummers2001
      @yummers2001 Před 2 lety

      Any chance this can be added as an annotation to the video at that point? I fell into the same trap! Otherwise - awesome video. Keep up the great work!

    • @mariusespejo
      @mariusespejo  Před 2 lety +1

      Not after it’s published sorry

    • @oudom_nohara
      @oudom_nohara Před 2 lety

      @@mariusespejo Thanks

    • @tobiasschafer1658
      @tobiasschafer1658 Před 2 lety

      And maybe something I am missing is some notes about the logout. Currently I am calling .logout() on the request AND calling session.destroy(). Maybe only the last one would be sufficient as it removes the complete session anyways ;-)

  • @sailormetz7148
    @sailormetz7148 Před rokem +29

    A problem I encountered: if you use argument names other than 'username' and 'password' for local strategy, you must specify them as options in local.strategy in super({ usernameField: 'otherName1', passwordField: 'otherName2' }).
    If you don't, it won't even throw any errors, you'll just keep getting a 401 Unauthorized error. This drove me insane. Hope this helps others avoid this mistake.
    But great tutorial regardless! Content like this makes the internet amazing.

    • @rajuc6438
      @rajuc6438 Před rokem +1

      Thank you so much man. You saved my life!!! It drove me insane for 2 hours. Thanks again

    • @MonkeyHandle001
      @MonkeyHandle001 Před 11 měsíci

      You are my savior, digital Jesus, God in CZcams. you saved my 8 hours.

    • @zflxw
      @zflxw Před 7 měsíci

      Thank you very much, you saved me so much trouble

    • @rumble1925
      @rumble1925 Před 2 měsíci

      Oof. Thanks bro, I thought I was going insane, not seeing any logs or anything.

    • @osarumenizedonmwen3670
      @osarumenizedonmwen3670 Před 18 dny

      thank you so much bro holy shit

  • @kinopiskfreepromocode5546
    @kinopiskfreepromocode5546 Před 2 lety +12

    The best tutorial i watched so far. Author tells the info clearly and without any useless data. So, i want to say that i was here when the num of followers had been 7k

  • @foofighterdaz
    @foofighterdaz Před 2 lety +9

    Can't thank you enough for this Marius, excellent content, pitched and paced perfectly.

  • @thecastiel69
    @thecastiel69 Před 3 lety +16

    This tutorial I wanted today, what a coincidence

  • @janphillips7177
    @janphillips7177 Před 2 lety

    Thank you! Very useful. I appreciate your descriptions and of Sessions and JWTs! All the best.

  • @h.w.b.9503
    @h.w.b.9503 Před rokem +1

    Thank you so much for this tutorial, it helped clear up so much of my confusion. All the examples of different Passport strategies are written using ES6 modules, but the documentation for Nest is with classes. Your video helped translate the difference and finally got my code to work. Very clear and well explained --signed a junior developer that only learned ES6 Javascript in my bootcamp XD

  • @xZunaii
    @xZunaii Před 2 lety +12

    I highly appreciate you going throug the code roughly and also briefly explaining the NPM packages which you're using / recommending. It's really fun coding along and learning in this video!

  • @paolotessarolo8927
    @paolotessarolo8927 Před 2 lety

    Best tutorial on NestJs authentication so far. Thanks a lot!

  • @tulionavarro6543
    @tulionavarro6543 Před 2 lety

    Tks once again! You make this easy with yours explanations.. each of details, make a difference.

  • @FunkyToe369
    @FunkyToe369 Před 2 lety +6

    Thanks for spending the time explaining each part and drawing the parallels to his we would do it in express.
    Really helped me understand how to accomplish session auth. Felt a bit lost when the docs only covered JWT auth and all the tutorials I found were showing me the code to make it work... But not why it worked haha

  • @quamzgraphix9826
    @quamzgraphix9826 Před rokem +1

    your nest js contents are soo good. keep it up marius

  • @asogbaibrahim9618
    @asogbaibrahim9618 Před rokem +1

    I love this tutorial. Clear as Spring water 💯

  • @jamaludinsalam
    @jamaludinsalam Před 2 lety

    Thankss! very usefull. in the last two days, i got Understand this Framework because of you, thank man🙏
    Keep it up

  • @MisaoM
    @MisaoM Před 2 lety +1

    Absolutely awesome tutorial, thank you so much! Your explanation is very clear and to the point, you're a fantastic teacher! :D

  • @usmanakram5458
    @usmanakram5458 Před 2 lety +2

    Such a masterpiece bro♥️ everything is perfect in this video 🏳️🙌

  • @seanki
    @seanki Před 2 lety +4

    Awesome tutorial thanks, I love that you included regular sessions as well and not ONLY a JWT implementation. Kudos!

  • @amadeuszrogowski6643
    @amadeuszrogowski6643 Před 2 lety

    These video series are awesome! Thank you Marius :)

  • @axelle9764
    @axelle9764 Před 4 měsíci

    Great tutorial! Very detail and useful. Keep up the good work

  • @user-ux9ud7gf6q
    @user-ux9ud7gf6q Před 2 lety

    Thank you so much for making this video! I loved it 😍

  • @jazun33
    @jazun33 Před 3 lety

    This was IMMENSELY helpful. THANK YOU!

  • @josipkes
    @josipkes Před 4 měsíci

    Extremely valuable content, thanks.

  • @bossmusa9075
    @bossmusa9075 Před rokem +1

    Even today i remember how i asked the question below the similar type of video about jwt and you reply back really fast althought your video was already great. As i see you still answers the questions and its impresive.

  • @meakdararoath1691
    @meakdararoath1691 Před rokem

    love your videos dude very clear explanation

  • @AliAliOxenFree
    @AliAliOxenFree Před rokem

    this is an excellent video. your explanation is spot on. thank you for taking the time to make these

  • @musbell
    @musbell Před 2 lety

    Thanks, @Marius! The video is so helpful, I really learnt a lot.

  • @germanwibaux6923
    @germanwibaux6923 Před 2 lety

    Excellent tutorial and better explanation!

  • @abhishekchintagunta8731

    Good job Marius, really appreciate your explanation. As I am transitioning to IT side, I find these videos very helpful.

    • @mariusespejo
      @mariusespejo  Před 2 lety

      Awesome, I wish you luck on your transition!

  • @dj-davo-mtz
    @dj-davo-mtz Před 10 měsíci

    Great video! It helps me a lot, thank you!

  • @OetziOfficial
    @OetziOfficial Před 2 lety +5

    Dude, after 4 days struggling you opened my eyes. They should add all of this in their documentation. You are a gold tressure!

    • @OetziOfficial
      @OetziOfficial Před 2 lety

      @Dev Guy I read the documentation first and in the span of 4 days, probably 100 times :D I actually started the project because I loved the documentation, its just on spot, with a few missing parts :)

    • @mariusespejo
      @mariusespejo  Před 2 lety +13

      Docs are definitely very good but it’s not always intuitive to everyone. Simply saying just read the docs is like telling people don’t go to school just read the text books….

    • @sophektounn6422
      @sophektounn6422 Před 2 lety +1

      I’m been looking for this. Thank you thank you. Would git repo of this code.

    • @h.w.b.9503
      @h.w.b.9503 Před rokem

      @Dev Guy I looked at and read the documentation from Nest and Passport. The main problem for me with the documentation is Nest is all classes and Passport documentation show you how to configure the different strategies in ES6. This video is literally the only resource I've found (and I searched for over a week) that explains that (a) passport is initiated when it is included in the correct provider array and you do not need passport.use() as explained in the Passport docs and (b) the UseGuard is registering the strategy and there is no need for passport.register(), again, as explained in the Passport docs

  • @mochamadrasyad338
    @mochamadrasyad338 Před 10 měsíci

    Awesome !! 🔥🔥, Thank you very much

  • @pranavyeole102
    @pranavyeole102 Před 2 lety

    This was definitely very useful. Thank you so much 😁

  • @cholasimmons
    @cholasimmons Před 11 měsíci

    That walkthrough at @23:45, priceless!
    So there's actually a guard on the route but you can login with the right body data? neat!!

  • @bgabriel7581
    @bgabriel7581 Před 3 lety

    Thanks for your video, i loved!!!

  • @vianch_tog
    @vianch_tog Před 2 lety

    Really really good fundamental tutorial!!!!
    thanks

  • @visualbonus8880
    @visualbonus8880 Před 10 měsíci

    This was awesome!

  • @ladanski
    @ladanski Před 3 lety

    Thanks for your content Marius. They are immensely helpful.

    • @mariusespejo
      @mariusespejo  Před 3 lety +1

      I’m glad! thanks for stopping by to comment

    • @ladanski
      @ladanski Před 3 lety

      @@mariusespejo THANK YOU 😎👍🏾

  • @maxbraun6271
    @maxbraun6271 Před 10 měsíci

    Great video thank you!

  • @darpananeja6755
    @darpananeja6755 Před 2 lety +1

    So glad to know that you are following the official NestJs documentation! I also do the same.

    • @mariusespejo
      @mariusespejo  Před 2 lety +1

      Honestly it’s some of the best docs I’ve seen!

  • @kobakamladze4175
    @kobakamladze4175 Před rokem

    Thank you for your effort!

  • @mohammedlotfy
    @mohammedlotfy Před 3 lety

    Great vid Marius we expect more 👏👏

  • @faez322
    @faez322 Před 2 lety +1

    Awesome, please continue ;)

  • @thelanelim92
    @thelanelim92 Před 2 lety

    Another great video Marius!

  • @jaumoso23
    @jaumoso23 Před rokem

    Thank you so much for this tutorial

  • @devbel
    @devbel Před 11 měsíci

    Great one 👌 Thanks

  • @hasst9261
    @hasst9261 Před 3 měsíci

    Cool content
    Rly helpful
    Ty!

  • @thomasdaquinzomahounhele8889
    @thomasdaquinzomahounhele8889 Před 11 měsíci

    thank you very much, your work is clear and it is very easy to follow you through the whole video

    • @mariusespejo
      @mariusespejo  Před 11 měsíci +1

      Thank you Thomas! Glad you think so!

  • @warpmonkey
    @warpmonkey Před 2 lety

    Thanks for the great video!

  • @josephbandawe8722
    @josephbandawe8722 Před 2 lety

    You are awesome! You cleared some very problematic issues for me. Thanks

  • @AnthonyDev
    @AnthonyDev Před 2 lety

    Thanks, great explanation.

  • @SergiySev
    @SergiySev Před rokem

    thank you so much for this tutorial!

  • @carlosteixeira4304
    @carlosteixeira4304 Před rokem

    Great tutorial bro. It's easy undestandable even to a beginner like me. Nice Job!

  • @kthalyn001
    @kthalyn001 Před 3 lety

    Hi Marius, thank you very much for your video. I hope your channel will grow more and more. Have a nice day :D

    • @mariusespejo
      @mariusespejo  Před 3 lety

      thanks Badinescu! glad you’re finding the channel useful!

  • @jarvisprestidge
    @jarvisprestidge Před 3 lety +1

    Awww yiss another Marius Espejo Nest vid 🔥

  • @leucthinh3226
    @leucthinh3226 Před rokem

    I appreciate what you did for community

  • @markopavic7012
    @markopavic7012 Před 3 lety

    Clean and clear , great tutorial...

  • @sleepaleart12
    @sleepaleart12 Před 2 lety +2

    Thank you for all these NestJS tutorials they are really helpful!

  • @milightingdesign3612
    @milightingdesign3612 Před 2 lety

    Thanks Marius your explanation was very clear and with details. This help me to add authentication to my project. Your content is awesome and very complete. Thank you so much for this video. I can't even say how much this content help me. thanksssssssss

    • @mariusespejo
      @mariusespejo  Před 2 lety +1

      I’m glad to help 😄 thanks for stopping by to comment!

    • @milightingdesign3612
      @milightingdesign3612 Před 2 lety

      @@mariusespejo thanks to you for create this video

  • @fernandogomez83
    @fernandogomez83 Před 2 lety

    Great video!

  • @LasekToJa
    @LasekToJa Před 3 lety

    Love your videos, thank you for help.

  • @manishupadhyay4519
    @manishupadhyay4519 Před 3 lety +8

    Thanks a lot Marius! for Authentication session. Very well crafted beautifully explained.
    Just 1 suggestion if you could put this session over git. Would be great to look at the code and get relate it post watching video.
    Keep up the good work!!!
    All The Best!!

  • @MartinezFortino
    @MartinezFortino Před 2 lety

    Very useful info. Thank you for the patient and detailed explanation.

  • @nikelborm
    @nikelborm Před 2 lety

    It`s awesome work! Thx, broo

  • @pavolslovak3063
    @pavolslovak3063 Před 2 lety

    Very understandable. You helped me, thanks :)

  • @thongtech1984
    @thongtech1984 Před 2 lety

    Yes, another awesome awesome videos,

  • @mariusespejo
    @mariusespejo  Před 3 lety +26

    00:00​ - Intro
    03:35​ - Initial routes
    04:41​ - UsersService
    07:50​ - AuthService
    10:40​ - Implementing passport-local strategy (username/password login)
    18:08​ - AuthGuards
    23:25​ - Summary of local login flow
    29:02​ - Guard to check if user is authenticated
    31:41​ - Setting up sessions
    40:37​ - Summary of login with sessions flow
    44:25​ - Setting up JWT strategy, signing and validating
    1:00:25​ - Summary of JWT strategy flow
    1:04:22​ - Conclusion
    1:05:20​ - Outro

  • @argya2073
    @argya2073 Před 7 měsíci

    thank you marius, your are awesome

  • @abubakarsani3463
    @abubakarsani3463 Před 10 měsíci

    This is excellent

  • @elrenzo
    @elrenzo Před 2 lety

    Amazing , thanks 😀

  • @sherifyousry5586
    @sherifyousry5586 Před 2 lety

    Very good job , Thanks a lot!

  • @tukuyoma
    @tukuyoma Před 2 lety +1

    Great video

  • @mbarekamehry8788
    @mbarekamehry8788 Před 2 lety +1

    Your effort is highly appreciated, Marius. Very helpful thanks!

  • @Bryan-bh7cy
    @Bryan-bh7cy Před rokem

    you are a legend

  • @swapnilcodes
    @swapnilcodes Před rokem

    Awesome !

  • @josegonzalez-jg1kj
    @josegonzalez-jg1kj Před 2 lety

    Excelent!

  • @Thilina4321
    @Thilina4321 Před 3 lety +1

    Thank you very much

  • @DevNiklesh
    @DevNiklesh Před 3 lety +2

    Best Nest.js content on YT so far.. Keep up the good work man @Marius

  • @user-ez6xb3rf3p
    @user-ez6xb3rf3p Před 3 lety +17

    You are gonna be famous soon

  • @bozabonilla
    @bozabonilla Před 2 lety

    I looking for this same but with graphql, good video my friend, it will help me

  • @abidalisidd
    @abidalisidd Před 2 lety

    There are so many classes you have created. It is good for separation of concern as you said. There should be a slide to explain the flow of uses of those classes. Ex: Class A used by Class b and Class b used by Class C. This will make it very easy to understand to the viewers.

    • @mariusespejo
      @mariusespejo  Před 2 lety +1

      Everything in nestjs is a class, don’t over think it, each one has a given purpose which you can usually easily determine by naming conventions, e.g. guard, controller, strategy, service, etc.

  • @aben7810
    @aben7810 Před rokem

    over separation of concerns. thanks for the tutorial anyway. I don't know why Nest is making everything complicated, yet people enjoying it, frankly.

    • @mariusespejo
      @mariusespejo  Před rokem +1

      Convention over configuration. You learn how to do this stuff once for a nest app, and can probably jump to any other nest app that will mostly be structured the same.
      Try making 5 different devs build the same API using express and they likely will come up with their own patterns and conventions because Express is too flexible/minimal. A large express app can easily become spaghetti. Eventually you realize you need conventions and defined architectures, plus you’d also benefit with adding TS… at which point you might as well just use Nest.
      Alternatives outside express/nest? Yeah there’s a couple. Try comparing the features and their overall ecosystem and you’re likely to find that it’s not as great. But of course YMMV

  • @ashishkumari-yg4gn
    @ashishkumari-yg4gn Před rokem

    Thank you sir

  • @tastaslim
    @tastaslim Před 3 lety

    Awesome man

    • @mariusespejo
      @mariusespejo  Před 3 lety

      🙏

    • @tastaslim
      @tastaslim Před 2 lety

      @@mariusespejo Can you make a Role-based access control video in Nest where we protect APIs using scopes.

  • @romanpshenichnyy9837
    @romanpshenichnyy9837 Před 2 lety

    Thanks a lot man, that was a super good material for me. Hope u will get the best in this life, good luck!

  • @sarvarumurzakov4332
    @sarvarumurzakov4332 Před 2 lety

    Awesome. Your Tutorials about Nest are the best in CZcams, even better than in Udemy

  • @adeyemisunday6866
    @adeyemisunday6866 Před rokem

    Marius the Genius....#Legend

  • @canmertinyo
    @canmertinyo Před 11 měsíci

    Thanks :)

  • @lasantharangakumara9263

    Thank You :) :)

  • @JamesBower
    @JamesBower Před 2 lety +2

    It would be terrifically useful if you would build the client side login flow that connects with the JWT strategy. This tutorial was really clear and concise.

    • @mariusespejo
      @mariusespejo  Před 2 lety

      Thanks, will consider it! For the most part the client-side is really just all about managing/storing that jwt somewhere and making sure it’s included in the headers of each request to your API. I’ll try to make a video about it sometime.

  • @kartikgarasia5685
    @kartikgarasia5685 Před 2 lety

    Very height quality content! Thanks Marius.

  • @ms0615122
    @ms0615122 Před 2 lety

    Hi, Marius I got a question, why the method validate that in JwtStrategy return the object coordinates to req.user at 1:02:42?
    Thanks 🙏

  • @resqiar
    @resqiar Před 2 lety

    Thank you so much for your effort making this!

  • @oddfeeling7956
    @oddfeeling7956 Před 2 lety

    Your background image is the hero image of my portfolio lmao

  • @dylanbourbotte3660
    @dylanbourbotte3660 Před 2 lety

    Thanks

  • @robertkaminski1781
    @robertkaminski1781 Před 3 lety

    Nice would be part 2 with refresh token. Tanks for video. ( I m from Erick )

  • @ebisan7856
    @ebisan7856 Před 3 lety

    Thank you

  • @MultiShokk69
    @MultiShokk69 Před rokem

    Awesome tutorial like always thank you,
    If you can do some new tutorial in vuejs / nestjs it will be awesome

  • @kurtestacion6113
    @kurtestacion6113 Před 3 lety +16

    Can you do more of nestjs with graphql like auth and/or microservices. That would be a unique content!

    • @mariusespejo
      @mariusespejo  Před 3 lety +12

      will definitely look into that more, I’m still learning a lot of the best practices with graphql myself

    • @yazeerahamed763
      @yazeerahamed763 Před 3 lety

      second that

    • @francisabonyi7115
      @francisabonyi7115 Před 2 lety

      @@mariusespejo Can't wait to learn that combination from a master like you

    • @mariusespejo
      @mariusespejo  Před 2 lety +2

      hey folks, just following up: new video just posted on doing this same auth topic but in graphQL specifically

  • @kimhyungchae
    @kimhyungchae Před 3 lety

    잘하네요👍

  • @vincent-thomas
    @vincent-thomas Před 2 lety

    This was soo good! Please post (pun intended) a video where you handle sign up and remove account!!!

    • @vincent-thomas
      @vincent-thomas Před 2 lety

      With JWT!

    • @mariusespejo
      @mariusespejo  Před 2 lety

      Thanks! Will consider a specific video on that topic. Not really much to it though, sign-up is basically almost the same as login, but obviously you’d be adding to a db table of users, and removing is simply deleting that record