NestJS JWT Authentication Tutorial

Поділитися
Вставка
  • Опубліковано 16 січ 2025

КОМЕНТАРІ • 91

  • @AdityaRaj-lj5wf
    @AdityaRaj-lj5wf 5 місяців тому +7

    an absolute GOAT video on this topic. The clarity I gained after implementing everything in this video is just so immense. Thanks a ton @Anson !

  • @biscuitdelicious5410
    @biscuitdelicious5410 8 днів тому

    Such a good tutorial.
    Took me a while to understand why the Strategy is after the AuthGuard and other important elements on how does Authentication works but overall great job at explaining and keeping it simple. Received a subscriber!

  • @kennethsutherland6926
    @kennethsutherland6926 4 місяці тому +1

    Brilliant my man. Very clear and descriptive instructional video on NestJs JWT auth. I would advise any developer who intends to use NestJs as their backend to watch this video for a clear understanding of how you can authenticate users from any front end application.

  • @se1yagyn
    @se1yagyn 7 місяців тому +4

    Very well structured video. Very nice explained. A wish from my side would be a Role Base Login now on top of this JWT Login. So an admin will redirect to another place then the regular user in the frontend bases on the login response

  • @arjunrnair5506
    @arjunrnair5506 2 місяці тому

    Amazing video...never have the concept been more clear to me

  • @محمد-م5ث1ش
    @محمد-م5ث1ش Рік тому +2

    I like your videos about nest, they're unique and really informative!

  • @mootalabs
    @mootalabs 4 місяці тому

    A very comprehensible video ever about the topic. Thanks man

  • @Leon0_0
    @Leon0_0 Рік тому +1

    Your videos are absolutely amazing and very informative, just keep up the great work.

  • @Demo-df2vr
    @Demo-df2vr 8 місяців тому +1

    Awesome tutorial, really helped me out! (Um salve do Brasil pra todo mundo que estiver lendo!)

  • @mustafa-ahmed-dev
    @mustafa-ahmed-dev 6 місяців тому

    Amazing explanation, keep up the good work
    Can't wait to see the next episodes

  • @davilucciola3362
    @davilucciola3362 10 місяців тому +3

    Tutorial very good man! Thank you so much!
    Another brazilian (🇧🇷) here?

  • @chairilashar7022
    @chairilashar7022 Рік тому +2

    Hello sir, can i request a future playlist for nest with redis?

  • @NeerajSharma-k1u
    @NeerajSharma-k1u 13 годин тому

    good content! Thanks for nice explanation

  • @mohsenmostafavi5028
    @mohsenmostafavi5028 Рік тому +1

    Awesome
    I'm excited about next golang video

  • @ernestsdane3510
    @ernestsdane3510 Рік тому +1

    This is great! I would love to see session auth implementation and websocket securing

  • @jhoubu
    @jhoubu 9 місяців тому +1

    Very good video.
    Question, what themes do you use in vscode?

  • @geraldnwanze989
    @geraldnwanze989 10 місяців тому +1

    okay, so i keep getting unauthorized when using the local guard. i decided to check and found out that the local strategy was not hit during the request

    • @ansonthedev
      @ansonthedev  10 місяців тому

      Make sure the strategy file is being registered by passing it as a provider in the module

    • @geraldnwanze989
      @geraldnwanze989 10 місяців тому

      okay, i figured out the issue. had to modify the request in the local auth guard to match columns i use for validation

  • @varunvunnikrishnan4054
    @varunvunnikrishnan4054 Рік тому +1

    I can see the authservice class highlighted with red color due to error. Then, How are you getting the result ?

  • @AhmedHassan-sd1ty
    @AhmedHassan-sd1ty 5 місяців тому

    Very well explained. thanks

  • @BartSimpson-pm3bs
    @BartSimpson-pm3bs 10 місяців тому

    in thunder client, you can alse add the jwt in the auth section, no need in the headers section

  • @igmtink
    @igmtink 9 місяців тому +1

    sir anson it's seems like refresh token is missing? how we can implement two token? access token for short lifespan and refresh token for long lifespan that we are storing it on database

    • @ansonthedev
      @ansonthedev  9 місяців тому +1

      You just create a second JWT that lasts longer than the access token, and use that to "refresh" the access token.

    • @igmtink
      @igmtink 9 місяців тому

      @@ansonthedev it's the same procedure sir to create the refresh token? but on the auth.module.ts we set the "JwtModule" with expiration, how can I handle a two expiration for accessToken and refreshToken?

    • @ansonthedev
      @ansonthedev  9 місяців тому +2

      You can use the JwtService and call .sign() or .signAsync() and manually set the expiresIn property. That will override the setting you configured in JwtModule.
      e.g: this.jwtService.sign(user, { secret: '123', expiresIn: '123' })

  • @pierocruz6191
    @pierocruz6191 8 місяців тому

    Quite informative, nice job!

  • @gempf
    @gempf 5 місяців тому

    Hello, nice video. Why at 7:40 do you install @nestjs/passport and passport alone? I didn't understand that...:(

    • @ansonthedev
      @ansonthedev  5 місяців тому +1

      @@gempf because both of them are required to work with JWT

  • @overrevvv
    @overrevvv Рік тому +1

    Thank you so much for this amazing video!
    Btw I have one question regarding the font or extension you're using in your VS code setup, what exactly is responsible to create different font in some of the code for example at 4:26 in the function validateUser the parameter authPayloadDto have different font.

    • @ansonthedev
      @ansonthedev  Рік тому

      That's just how VS code often does it, I believe. The fonts are different because one of the names is the method name, and the other is a method argument. The font name is Operator Mono and the theme is Horizon.

  • @VsevolodPetrowsky
    @VsevolodPetrowsky 10 місяців тому

    tnx so much, man this video is awesome! U help me alot, dude, I hope u ll make more video, u a best on it

  • @le_grumpycat
    @le_grumpycat 6 місяців тому

    theres only one thing i couldn't understand about the guards and strategies, how do the guards know exactly which strategy we're using, since inside their code we dont refer to any specific strategy?

    • @sogobamimore8933
      @sogobamimore8933 2 місяці тому

      you can see that the AuthGuard we imported is from @nest/passport, they have written some clever codes behind the scenes. The moment we say LocalStrategy extends PassportStrategy(Strategy[which means local]) they have saved it. So once we said AuthGuard(local), they directly go for the LocalStrategy

  • @tpglitch
    @tpglitch 11 місяців тому +2

    Thank you so frickin much! Needed this for smth I'm working on 👀

  • @Trucker9-e7s
    @Trucker9-e7s 3 місяці тому

    why are you handling errors in the controller and not the service ?

  • @asadmehboob1300
    @asadmehboob1300 Рік тому

    Great video....can bun increase Nestjs speed?

  • @dawidgrabowski
    @dawidgrabowski 10 місяців тому

    Great explanation!

  • @muhammadsyaugi783
    @muhammadsyaugi783 7 місяців тому

    thanks man its very helpul for me

  • @lifeInGod2K
    @lifeInGod2K 11 місяців тому

    Well explained, thank you!!

  • @prashlovessamosa
    @prashlovessamosa Рік тому

    Thanks Anson.

  • @newquery685
    @newquery685 Рік тому +4

    Could you make one about the refresh token

  • @pratikmande
    @pratikmande 9 місяців тому

    i just want to know how to throw an HttpException instead of return null,

  • @wensa7041
    @wensa7041 5 місяців тому

    this is a god tier video

  • @MiguelPerez-py4ey
    @MiguelPerez-py4ey 5 місяців тому

    And how can I blacklist the token or something like that to handle the logout of the users?

  • @GustavoAlexanderHerreraPérez
    @GustavoAlexanderHerreraPérez 10 днів тому

    Beautifull!!!

  • @vageeshanvageesh5583
    @vageeshanvageesh5583 Рік тому +1

    The king anson is back!!!

  • @gregscolumn
    @gregscolumn 10 місяців тому +1

    Thanks for this, but I am having an error here, I am using email instead of username, when I test the login endpoint in and pass the correct email and password I still get the Unauthorised error coming from the local strategy, please is there any solution to this or is it that we can only use username to authenticate?
    Thanks once again

    • @ansonthedev
      @ansonthedev  10 місяців тому +1

      In the LocalStrategy file, where you are calling super(), you want to pass options and set "usernameField" to the field name. So for example, if the field name is "email" then the options would look like this:
      { usernameField: 'email' }

    • @gregscolumn
      @gregscolumn 10 місяців тому

      @@ansonthedev okay thanks, let me try it

    • @gregscolumn
      @gregscolumn 9 місяців тому +2

      hey, so I got to the jwt guard part, and I keep getting the same Unauthorized message even after using the correct JWT Code, since I am using email instead of username? is there anything I need to pass super() ?
      Thanks

    • @jaydraws2019
      @jaydraws2019 8 місяців тому +1

      I got the same problem. Decided to followup on another tutorial. After wasting hours, I've moved on to another tutorial lol.

  • @thetrungphaninh8274
    @thetrungphaninh8274 9 місяців тому

    I follow your video but I encountered the problem "property 'user' doesn't exists on type 'Request'" when I call req.user. Can you help me fix this bug.

    • @ansonthedev
      @ansonthedev  9 місяців тому

      You need to make sure you have both Local and Auth guard. Check the code repository here and make sure you didn't miss anything: github.com/stuyy/nestjs-passport-jwt-example/

  • @sajjadhoviegar5950
    @sajjadhoviegar5950 5 місяців тому

    Thanks for the great tut! I have a question: if someone requests twice (or multiple times) for the login endpoint and it is successful, then there are two tokens that both are valid! What happens in this scenario? Is it okay or we should handle that too?

    • @ansonthedev
      @ansonthedev  5 місяців тому +1

      You can probably check if there's an existing JWT for the user before issuing another one.

  • @wallelignworkie8749
    @wallelignworkie8749 7 місяців тому

    the DB is?

  • @TM-jb8bw
    @TM-jb8bw 11 місяців тому

    Awesome 🎉

  • @deepikamateti17
    @deepikamateti17 Рік тому

    How is the guard and strategy mapping happening is it because of the value in Authguard and it checks for that value strategy file name or is it because of passport import? also can I have 2 local strategies?

    • @ansonthedev
      @ansonthedev  Рік тому

      The guard invokes the Strategy, basically the string argument you pass into the AuthGuard() decorator lets NestJS know which Strategy to call. For example, if you use Google, you'd pass "google" into the AuthGuard decorator like this: AuthGuard("google"). Then NestJS will check if there is a Google Strategy registered, if not it will throw a "strategy not found" error or something similar indicating the strategy does not exist.
      Not sure what you mean by "2 local strategies", but you can have the standard way of authenticating, using username/email and password. If using JWT, you'd need JWT and Local strategies. Anything else would be 3rd party such as OAuth2 using something like Google or Discord to authenticate.

    • @deepikamateti17
      @deepikamateti17 Рік тому

      @@ansonthedev Got it thanks!

  • @SashaYursa
    @SashaYursa 11 місяців тому +1

    so difficult for me, too much steps to keep in mind, maybe i shoud rewatch video

    • @sogobamimore8933
      @sogobamimore8933 2 місяці тому

      sorry bro did you figure it out?

    • @SashaYursa
      @SashaYursa 2 місяці тому

      @ hah, thank you for your concern, actually I moved away from nest js and switched to react native

    • @biscuitdelicious5410
      @biscuitdelicious5410 29 днів тому

      @@SashaYursa ?? NestJS is a server-side framework while RN is for UI 🙂

    • @SashaYursa
      @SashaYursa 29 днів тому +1

      @@biscuitdelicious5410 yep, now i’m frontend dev:(

  • @gregscolumn
    @gregscolumn Рік тому

    Thanks for uploading this video.
    Could you please make one for adding and getting user specific data. Like user can only see the data they add to the server. Been struggling with that lately.
    Thank ❤

  • @dr-Jonas-Birch
    @dr-Jonas-Birch Рік тому +2

    Good info but this video doesn't have that "Anson soul" that we have known and loved, and which makes your videos very special. I think you are too conscious about not talking too fast. And don't cut, it makes you lose the rhytm. Rest is great though. JB

  • @cryptotechita4889
    @cryptotechita4889 8 місяців тому

    Legend

  • @фанатпуджа2007
    @фанатпуджа2007 2 місяці тому

    goat

  • @kamleshbachani8132
    @kamleshbachani8132 Місяць тому

    booo..lean 24:26

  • @gempf
    @gempf 4 місяці тому

    Hello, why the `return super.CanActivate(context)` from jwt.guard.ts doesn't work?

  • @碰偉
    @碰偉 7 місяців тому +1

    Thank you for your video, but I referred to the official documents and saw similar writing methods. I think the order of decorators should be that post should be executed first. It would be more intuitive, but in theory, calling rest will execute all the decorators of function. , for your reference
    @UseGuards(LocalAuthGuard)
    @Post('login')
    login(@Req() req: Request) {
    return req.user;
    }