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

แชร์
ฝัง
  • เผยแพร่เมื่อ 28 ก.ย. 2024

ความคิดเห็น • 423

  • @mariusespejo
    @mariusespejo  2 ปีที่แล้ว +49

    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 2 ปีที่แล้ว

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

    • @yummers2001
      @yummers2001 2 ปีที่แล้ว

      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  2 ปีที่แล้ว +1

      Not after it’s published sorry

    • @oudom_nohara
      @oudom_nohara 2 ปีที่แล้ว

      @@mariusespejo Thanks

    • @tobiasschafer1658
      @tobiasschafer1658 2 ปีที่แล้ว

      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 ;-)

  • @cholasimmons
    @cholasimmons ปีที่แล้ว

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

  • @bossmusa9075
    @bossmusa9075 ปีที่แล้ว +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.

  • @sailormetz7148
    @sailormetz7148 2 ปีที่แล้ว +33

    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 ปีที่แล้ว +1

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

    • @MonkeyHandle001
      @MonkeyHandle001 ปีที่แล้ว

      You are my savior, digital Jesus, God in TH-cam. you saved my 8 hours.

    • @zflxw
      @zflxw 10 หลายเดือนก่อน

      Thank you very much, you saved me so much trouble

    • @rumble1925
      @rumble1925 5 หลายเดือนก่อน

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

    • @osarumenizedonmwen3670
      @osarumenizedonmwen3670 3 หลายเดือนก่อน

      thank you so much bro holy shit

  • @abhishekchintagunta8731
    @abhishekchintagunta8731 2 ปีที่แล้ว

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

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Awesome, I wish you luck on your transition!

  • @JamesBower
    @JamesBower 2 ปีที่แล้ว +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  2 ปีที่แล้ว

      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.

  • @AliAliOxenFree
    @AliAliOxenFree ปีที่แล้ว

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

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      Appreciate the feedback! Thanks!

  • @vincent-thomas
    @vincent-thomas 2 ปีที่แล้ว

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

    • @vincent-thomas
      @vincent-thomas 2 ปีที่แล้ว

      With JWT!

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      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

  • @kthalyn001
    @kthalyn001 3 ปีที่แล้ว

    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  3 ปีที่แล้ว

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

  • @musbell
    @musbell 3 ปีที่แล้ว

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

  • @vanshdubey21
    @vanshdubey21 4 หลายเดือนก่อน +1

    VERY VERY HELPFUL VIDEO

  • @adeyemisunday6866
    @adeyemisunday6866 2 ปีที่แล้ว

    Marius the Genius....#Legend

  • @argya2073
    @argya2073 10 หลายเดือนก่อน

    thank you marius, your are awesome

  • @maxbraun6271
    @maxbraun6271 ปีที่แล้ว

    Great video thank you!

  • @bozabonilla
    @bozabonilla 3 ปีที่แล้ว

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

  • @thongtech1984
    @thongtech1984 2 ปีที่แล้ว

    Yes, another awesome awesome videos,

  • @hasst9261
    @hasst9261 5 หลายเดือนก่อน

    Cool content
    Rly helpful
    Ty!

  • @jaumoso23
    @jaumoso23 ปีที่แล้ว

    Thank you so much for this tutorial

  • @warsisarjeelrahman3940
    @warsisarjeelrahman3940 3 ปีที่แล้ว +1

    Can you please make a complete authentication tutorial with nestjs and react? Love the nest videos.

    • @mariusespejo
      @mariusespejo  3 ปีที่แล้ว +1

      will definitely consider it!

    • @kunheelim881
      @kunheelim881 3 ปีที่แล้ว +1

      @@mariusespejo thanks for this video Marius
      i'm studying jwt Login authentication with nest.js, react too.
      complete authentication tutorial(refresh token, logout ...stuffs) will be very helpful for me
      I want you to refer to making a video for this.
      Thanks!

    • @warsisarjeelrahman3940
      @warsisarjeelrahman3940 3 ปีที่แล้ว

      @@mariusespejo Love your tutorials, man.

  • @bgabriel7581
    @bgabriel7581 3 ปีที่แล้ว

    Thanks for your video, i loved!!!

  • @MultiShokk69
    @MultiShokk69 2 ปีที่แล้ว

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

  • @romanpshenichnyy9837
    @romanpshenichnyy9837 3 ปีที่แล้ว

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

  • @eliotistube
    @eliotistube 3 ปีที่แล้ว

    Great video Marius!
    You made clear a lot of points around authentication that were a bit confusing to me.
    Could you possibly make a video about authentication using JWTs with NestJS and GraphQL (code first)?
    Thanks again!

    • @mariusespejo
      @mariusespejo  3 ปีที่แล้ว

      Thanks Takis! Definitely looking to dive into more graphql stuff

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว +1

      fyi just published a new video specifically on that topic!

  • @mobinal5429
    @mobinal5429 2 ปีที่แล้ว

    Pretty long but worth it!

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Thanks! I’m trying to get better at explaining complex stuff in shorter time but it’s not easy haha

  • @Fakhranyy
    @Fakhranyy ปีที่แล้ว

    Great work ! , but I was wondering , it's too many steps I think I couldn't all of these from my memory , I think it's hard at first and it's okay if I followed the documentation to implement it .. what's your opinion about that ?
    all love from Egypt

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      I mean unless you do this type of work often it’s not really something you would memorize. For most applications you probably only set up auth once and adjust it a few times. I would definitely suggest having the documentation as reference. It’s ultimately the fundamentals of auth and session management that you need to understand and know well, then you can always reference docs if you need a refresher

  • @alesofton
    @alesofton 2 ปีที่แล้ว +1

    thanks but don't work for me... always say error 401 unathorized

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Well there’s logic to why it would not be authorized, that’s exactly what guards are for. Do some logging to find out why…e.g. maybe you tested with expired/wrong token, maybe user wasn’t found, maybe your sessions (if you’re doing sessions) aren’t set up correctly etc. etc. it’s not magic there are simple boolean logic behind your guards that determines does the request move forward or not, you just need to figure out the why and see if you made a configuration mistake

  • @culttm
    @culttm 3 ปีที่แล้ว

    Thanks for your video! Can you explain how to implement the server side api calls with session based token refreshing?

    • @mariusespejo
      @mariusespejo  3 ปีที่แล้ว +1

      The gist of it is that you need to store your refresh toke somewhere, e.g. perhaps in your session store Every time your service needs to use the access token, check if it’s expired and if so refresh it using your stored refresh token. What the refresh request looks like differs depending on your identity provider, but usually it’s just a POST request with your refresh token attached

    • @culttm
      @culttm 3 ปีที่แล้ว

      ​@@mariusespejo it is clear for me, thanks. but just imagine that you have at least 2 tabs with one user session and create several requests at the same time. the first request recieves 401 or checks an access token's expiry and tries to refresh one & renew in a session. it can take several ms. The parallel request tries to do the same thing and uses already expired access and refresh tokens and recieves an error "Token is invalid" . Maybe there should be smth like a lock mecanism. Or this script is wrong in the first place. I think it seems to be a great topic for the next video)

    • @mariusespejo
      @mariusespejo  3 ปีที่แล้ว

      Yup will consider a follow up video. That’s definitely a valid edge case, there are several different ideas e.g. perhaps proactively check token expiration on an interval, not just on requests, or maybe flag the session to mark it as “refreshing” (similar to your locking idea) etc.. I would first consider though how likely that scenario would really happen for your use case. I can’t imagine refreshing really takes that long. Also something to consider is that in your scenario would it not simply just refresh at both requests? Meaning the second would just overwrite the token update of the first. If you make sure to wait for the refresh to complete on any request then I don’t see any real conflicts. Except for maybe when refresh tokens are rotated and become invalid, but again we’re talking about milliseconds here

    • @culttm
      @culttm 3 ปีที่แล้ว

      @@mariusespejo however this edge case is likely to happen. I would love to see your realization anyway. Maybe there will be some tricks or tips that could help me out!

  • @IanGem1121
    @IanGem1121 3 ปีที่แล้ว

    I've been looking for this. Can you do a video on nestjs database provider with mongoose?

  • @joebowbeer
    @joebowbeer 2 ปีที่แล้ว

    One bit of passport magic that I had to look up: the req.user property name is optional and can be changed in initialize()

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Can’t really think of better name than that though. Fyi in nest you can also create a custom decorator like @User() which can be set up to automatically give you the value of req.user

  • @aqezu
    @aqezu ปีที่แล้ว

    Hey Marius, old video now ik but still asking, do we need to have a JwtGuestGuard (e.g. for LOGIN route) ? If so, we need to recode a canActivate method right ?

    • @aqezu
      @aqezu ปีที่แล้ว

      To be more accurate, what I mean by GuestGuard is some kind of Guard that says « hey your token is still valid I can’t generate you another one / your token is missing/non-existent, I’ll generate one for you »

    • @aqezu
      @aqezu ปีที่แล้ว

      And btw any good practice to invalidate a user ? Maybe some kind of fullstack app would be cool to make a video of :D enjoyed your work as always tho ! :D

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      Hey Abriscout, sorry not sure I’m understanding the question. Did you watch the video in full? I believe I did cover having a guard that checks for the existence of a jwt on any routes that you protect, but that wouldn’t be on a login route. Not sure it makes much sense to check for a jwt on a login route when the login itself typically would generate the jwt. It is not the guard’s job to generate tokens… it’s purpose is to simply decide “should I let this user proceed or not”. E.g. it could check if the token is invalid or perhaps it’s expired, then it can respond with a status 401/403 to inform the client “hey you need to login and get a new token”. Which is why again, doesn’t make sense to check for the token at login, because you know they NEED one if they’re calling login. I think what you might be thinking about are refresh tokens, which are meant to automatically allow a client to get a new access token, basically extending the life of the session without needing to login again.
      As for your second question, there isn’t really a great way to invalidate a jwt…you’d have to somehow track the id of that token and maintain some kind of block list. This is also generally why you want access tokens to often have short expiration. If you were using sever-side session however, then you’re in full control with every session object, you could simply just have your store remove a session and that would effectively invalidate a user

    • @aqezu
      @aqezu ปีที่แล้ว

      @@mariusespejo Yeah I was confused by so many things, and then I discussed with devs that have show me some ways of how to do it. My question was not very clear, but basically it was about preventing user that is already logged in to access the login route :D Thanks !

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      Not really sure it’s that beneficial to do something like that. What if you wanted to allow multiple logins across different browsers/clients? The client app should be designed in such a way that it knows if the user is logged in (to prevent access to the login form and instead show logout button, for example). If a user somehow tries to login again then the client app should simply know to discard and replace any existing token, wherever it may be storing it. Or if you’re interested in some kind of invalidation then keep track of all created token IDs server-side and if the user logs in then invalidate any existing tokens they already were provided. Basically there are ways around getting the proper expected behavior without needing to restrict the login route

  • @mynameisjeff8559
    @mynameisjeff8559 ปีที่แล้ว

    BEST VIDEO

  • @insomnia6961
    @insomnia6961 ปีที่แล้ว

    Very good job on this one!
    i decided to go with session auth for my application and it works just like promised with insomnia and postman. I'm currently setting up a frontend with angular and do now face a problem. The Session Cookie is visible in the chrome dev tools network tab, but the cookie is not set at Application > Cookies.
    Can some one help me please
    (didn't find an answer on stack overflow)

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว +1

      Does your server response use the Set-Cookie header? developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

    • @insomnia6961
      @insomnia6961 ปีที่แล้ว

      @@mariusespejo thanks a lot for the reply!
      i had to intercept the outgoing requests from the angular app and add {withCredentials: true} and changing origin: '*' to allow-origin: 'mything' as well as allow-credentials: true in the BE. Otherwise the cookie is not set in FE nor shipped with the Request or it results in a cors error. I should have mentioned, that BE and FE are not running under the same domain, my bad, sorry.
      But thanks again for your quick reply! You are doing a serious job here and i didn't find anyone who comes close to your tutorials (sound quality, speed, explainations)
      Thanks alot for that.
      best regards!

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว +1

      Glad you figured it out and thanks for the feedback!

    • @leo-3r
      @leo-3r 5 หลายเดือนก่อน

      @@insomnia6961 can you share the code you used to fix this? I cannot figure this out... I have the same scenario here

    • @insomnia6961
      @insomnia6961 5 หลายเดือนก่อน

      @@leo-3r i changed to jwt in the mean time. The reason is, my system is deployed to firebase and app engine and gcp does strip all cookies for security reasons. (There is a specific token name that should work though, but it did not for me, so a switched to jwt)
      So i am sorry, but i cant tell you how i made it work back then

  • @toneyavuz8389
    @toneyavuz8389 ปีที่แล้ว

    I haven't seen that you edited the main.ts file.

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      There’s like an entire section that starts with editing that file. 31:41

  • @jamols09
    @jamols09 3 ปีที่แล้ว

    Is it required the we use 'username' & 'password' as the fields and not 'name' ? I get Unauthorized when I use name instead of username, (I've also changed property for comparison)

    • @mariusespejo
      @mariusespejo  3 ปีที่แล้ว

      No you can change it through the strategy options, make sure to look at the docs for it

  • @jessicamaria682
    @jessicamaria682 3 ปีที่แล้ว

    Thank you for this video!

  • @bigg565
    @bigg565 ปีที่แล้ว

    When I finish the local strategy without tokens or jwt first, I constantly get a 401 Error and that I am unauthorized, do You maybe know why and can help me out?

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      That means your validate() didn’t return or find a user. Or perhaps you’re incorrectly throwing the exception somewhere

    • @bigg565
      @bigg565 ปีที่แล้ว

      @@mariusespejo How can I check what it returns or maybe debug it?

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      You’re in charge of implementing that, as shown in the video. You have access to it

    • @bigg565
      @bigg565 ปีที่แล้ว

      @@mariusespejo I just checked my code and I did all as shown in the video and have basically the exact same code as in the video, but it still wont work.

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      And you’re able to log out that you’re getting a user back? Did you verify that the validate method is getting invoked? Is the strategy actually registered as a provider in the auth module?
      Those are some steps to debug. It’s important to have a fundamental understanding of how passport works and how it’s used in nest, and where might your errors be.
      Local strategy when done correctly should be able to give you back a user with the match username password.

  • @vinaykaithwas2973
    @vinaykaithwas2973 2 ปีที่แล้ว

    29:09 Session

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      There are timestamps in the description if you need it

  • @petvideosshorts2322
    @petvideosshorts2322 2 ปีที่แล้ว

    Hello brother.. can you please assist me on updating logged in user details without providing id in controller like @param(‘id’) id: string …

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      I mean updates ideally are going through your api/controller if it’s user driven. If you don’t want to pass in the ID then you have to already have it in session store.
      If it’s just the system making changes then just trigger logic to update the record in database/session. I would suggest posting a more detailed question in stackoverflow

  • @goodcoder4953
    @goodcoder4953 2 ปีที่แล้ว +1

    🙏 Please Give Me Git Hub Url of this Project

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Not on github at the moment sorry, consider following the tutorial from scratch, it honestly won’t take the long, most of the video is just me explaining the details

  • @haralc
    @haralc 2 ปีที่แล้ว

    I have put the /login inside the /user ... now I'm getting "circular dependency between modules" error.

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      You likely have services depending on each other.. it’s generally best to separate concerns as much as possible, e.g. I would not add /login inside your user controller. It’s better to do that in a stand-alone AuthController

    • @haralc
      @haralc 2 ปีที่แล้ว

      @@mariusespejo A Company has Employees, Employees have Company. Then how you'd take this? This roadblock is at module-level, not just Service. Can you do some real-world app? There's someone who did Facebook clone end-to-end, not just small bits of everything and hopefully someone is clever enough to piece things together.

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      You can resolve the circular dependency itself if you’d like: docs.nestjs.com/fundamentals/circular-dependency
      But the point is to avoid it in the first place. I can’t tell you how exactly to do that, you need to understand your own dependency tree. I don’t see how this has anything to do with auth (the topic of this video)

    • @haralc
      @haralc 2 ปีที่แล้ว

      @@mariusespejo I just mentioned that since we're talking about circular dependencies. Maybe "circular" is more on the negative side, I'll just put it as "two-way relationship", books-author, company-employee, library-books, hospital-patient and whatnot.
      I'm sorry if I got over excited and left my manners somewhere, but I had a great time learning the basics. So, great video. And so, would you please make a more advanced tutorial/demo -- something like a Facebook clone would be nice, or some website that is relevant today and of course with the use of this technology. Thanks in advance!

  • @etherofgodd
    @etherofgodd 3 ปีที่แล้ว

    hi @Marius Espejo thanks so much for the tutorial. i keep on getting this error ERROR [ExceptionsHandler] request.isAuthenticated is not a function. what do I do ?

    • @attranmanh8197
      @attranmanh8197 3 ปีที่แล้ว

      did u fix it? I can't not search for the solution :(

    • @mariusespejo
      @mariusespejo  3 ปีที่แล้ว +1

      IsAuthenticated specifically comes from passport, that means there is something missing in your configuration. Did you set up express-session and did passport.initialize() and passport.session()? The order of those 3 things is important. Finally did you add the serializers and registered it in your module?

    • @attranmanh8197
      @attranmanh8197 3 ปีที่แล้ว

      @@mariusespejo my error come before "Session setup", I followed your timestamp until "is.authenticated()" fault. I did replayed your vid 2 times but still have this error

    • @mariusespejo
      @mariusespejo  3 ปีที่แล้ว

      You have to setup passport and sessions completely, did you do all 4 things that I mentioned in the previous comment?

    • @attranmanh8197
      @attranmanh8197 3 ปีที่แล้ว

      @@mariusespejo I set up fully, but I'll try to create another proj to do it

  • @nomanahmedkhan6352
    @nomanahmedkhan6352 ปีที่แล้ว

    can u share this source code,?

  • @andriancabisada4313
    @andriancabisada4313 2 ปีที่แล้ว

    github repo please. haha

  • @thecastiel69
    @thecastiel69 3 ปีที่แล้ว +16

    This tutorial I wanted today, what a coincidence

  • @mariusespejo
    @mariusespejo  3 ปีที่แล้ว +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

    • @adnanhaider4038
      @adnanhaider4038 2 ปีที่แล้ว

      0

    • @muhammadharis2205
      @muhammadharis2205 ปีที่แล้ว

      req.isAuthenticated gives error ""request.isAuthenticated is not a function" at 29.02 section.

  • @МихаилЧон
    @МихаилЧон 3 ปีที่แล้ว +17

    You are gonna be famous soon

  • @kurtestacion6113
    @kurtestacion6113 3 ปีที่แล้ว +16

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

    • @mariusespejo
      @mariusespejo  3 ปีที่แล้ว +12

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

    • @yazeerahamed763
      @yazeerahamed763 3 ปีที่แล้ว

      second that

    • @francisabonyi7115
      @francisabonyi7115 2 ปีที่แล้ว

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

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว +2

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

  • @kinopiskfreepromocode5546
    @kinopiskfreepromocode5546 2 ปีที่แล้ว +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

  • @santiagazolara
    @santiagazolara 2 ปีที่แล้ว +2

    What about an email instead of a username - I never use usernames with my applications. It doesn't work by just switching username to email... but it doesn't take much more work either, just a simple mapping object in the right place.
    ```export class LocalStrategy extends PassportStrategy(Strategy) {
    constructor(private authService: AuthService) {
    super({
    usernameField: 'email',
    passwordField: 'password',
    });
    }
    async validate(email: string, password: string): Promise {
    const user = await this.authService.validateUser(email, password);
    if (!user) {
    throw new UnauthorizedException();
    }
    return user;
    }
    }```

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว +2

      Yup that’s exactly how you’d be able to do it

    • @foofighterdaz
      @foofighterdaz 2 ปีที่แล้ว

      Thanks for sharing this Jay! Killed me for about 2 hours.

  • @manishupadhyay4519
    @manishupadhyay4519 3 ปีที่แล้ว +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!!

  • @foofighterdaz
    @foofighterdaz 2 ปีที่แล้ว +9

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

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว +1

      Thank you! I appreciate the feedback

  • @FunkyToe369
    @FunkyToe369 3 ปีที่แล้ว +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

  • @batuhanbag5054
    @batuhanbag5054 2 ปีที่แล้ว +1

    If you have this error "ERROR [ExceptionsHandler] request.isAuthenticated is not a function" you should return request.isAuthenticated; instead of return request.isAuthenticated() at the authenticated.guard.ts file

    • @satyamprajapati3779
      @satyamprajapati3779 2 ปีที่แล้ว +1

      Thank you!!!!....You saved my time

    • @batuhanbag5054
      @batuhanbag5054 2 ปีที่แล้ว

      @@satyamprajapati3779 You’re welcome happy coding !

  • @Randito33
    @Randito33 หลายเดือนก่อน

    Thanks for this tutorial, I went through the NestJS docs a few times and tried to set this up myself but there was always something wrong. Your vid helped me finally get it all working!

  • @OetziOfficial
    @OetziOfficial 3 ปีที่แล้ว +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 3 ปีที่แล้ว

      @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  3 ปีที่แล้ว +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 2 ปีที่แล้ว +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 ปีที่แล้ว

      @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

  • @luckyardhika3781
    @luckyardhika3781 2 ปีที่แล้ว

    Are you stuck in 401 in protected route, bro? thats cause you to not show how succesfully request in protected route yes??

  • @akarihinata8975
    @akarihinata8975 2 ปีที่แล้ว +1

    Is it possible to login just after signup (register) ?

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Yeah don’t see why not

  • @usmanakram5458
    @usmanakram5458 2 ปีที่แล้ว +2

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

  • @xZunaii
    @xZunaii 2 ปีที่แล้ว +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!

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Glad you’re enjoying it!

  • @RealWorldMusicTheory
    @RealWorldMusicTheory 2 ปีที่แล้ว

    What happens when the JWT expires? Would the user have to login every 60 seconds? Does passport generate fresh tokens and handle them automatically?

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว +1

      60 seconds is obviously an unrealistic expiration that was only used an example.. you should decide what makes sense for the security of your application. If you want it to automatically renew for the user you can do that with refresh tokens, not sure if the passport strategy does that automatically. Anyways otherwise yes you’d have to have them login at expiration

  • @muhammadharis2205
    @muhammadharis2205 ปีที่แล้ว

    req.isAuthenticated gives error ""request.isAuthenticated is not a function" at 29.02 section.

  • @JorgeFrota-r6w
    @JorgeFrota-r6w หลายเดือนก่อน

    Hey Marius, just passing by to thank you, your video format is awesome.
    I love how you explain everything while showing the documentation. It really adds to us as developers, so that we know like "oh, so the information was here all the time!". It particularly helped me a lot.
    Keep up the good work!

    • @mariusespejo
      @mariusespejo  29 วันที่ผ่านมา

      Thanks man! Glad you found it useful 🙏

  • @Sebeklis
    @Sebeklis 2 ปีที่แล้ว

    Why people are using sessions? In both approaches the client side must securely save the “cookie” or the “jwt token”. The main difference is that in case of the JWT approach the server does not need to maintain a DB of sessionId for lookup

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      It’s a matter of where you want to store the session…. In a store or in jwt… note that if you have a lot of data for your user session having all of that in a jwt/cookies would be impractical, that’s just extra data you’re sending over the wire. So it depends on the use case. Also server-side sessions are significantly more secure in my opinion, you don’t have to worry about tokens being intercepted (which again will have some user data on it)

  • @tunghaotu8652
    @tunghaotu8652 2 ปีที่แล้ว +1

    Hi guys, i am stuck in the chapter guard to check if user is logged in. It is an error said "request.isAuthenticated()" is not a function. I console log the keys of request object and realize that the object dont have the isAuthenticated isUnauthenticated ,user. Any suggestion guys ?

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว +1

      It likely means either the guard or the strategy were not registered or configured correctly

    • @tunghaotu8652
      @tunghaotu8652 2 ปีที่แล้ว

      @@mariusespejo i have checked every step very clearly but can not figure out which step that i missed. Googling for days and have no hope man. The local strategy work as the video. But the authenticatedGuard implements CanActive not working. Do you have any idea for it ?

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Are you sure you registered your strategies as providers in the module?

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Did you actually setup sessions? Please note that in the video I explicitly said the guard won’t work until you actually have the sessions in place. That along with actually having the full passport local strategy working and correctly registered is what’s needed. Make sure to watch the rest of the video and don’t just stop at the point of error

    • @tunghaotu8652
      @tunghaotu8652 2 ปีที่แล้ว

      @@mariusespejo My bad.that is the missing piece . i have finished following your tutorial. that really helpful . thanks for your answer and making such a good video. have a nice day

  • @MahmoudAhmed-nq7ou
    @MahmoudAhmed-nq7ou 8 หลายเดือนก่อน

    (this.validate is not a function) this error had shown to me
    can someone help me please

  • @ash1982ok
    @ash1982ok 3 ปีที่แล้ว +2

    could you please share your source code?

  • @saikatjaman2004
    @saikatjaman2004 3 ปีที่แล้ว +1

    Hi Sir, Thanks for the osm Tutorial, can we have the git link for source code plz.

  • @waycambas150
    @waycambas150 7 หลายเดือนก่อน

    I got some error when request protected
    ERROR [ExceptionsHandler] Unknown authentication strategy "jwt"
    Error: Unknown authentication strategy "jwt"

    • @waycambas150
      @waycambas150 7 หลายเดือนก่อน

      oh I got this

  • @yazelkro7522
    @yazelkro7522 ปีที่แล้ว

    Hello, I have covered the first 30 minutes of the video, I keep getting this when using postman TypeError: Cannot read properties of undefined (reading 'validateUser'). I do not find the error, I have checked the documentation

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      That’s implemented in the AuthService around 7:50. Did you actually implement validateUser? Is it in the correct service?

  • @malinduupendra7117
    @malinduupendra7117 2 ปีที่แล้ว +1

    hi marius, in AuthenticatedGuard file i get error which is "request.isAuthenticated is not a function". may i know why i get that ?

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      You likely didn’t setup the local strategy and its guard correctly

  • @lakeman4101
    @lakeman4101 2 ปีที่แล้ว +1

    it would have been great to have your git hub repo to the project to interact well with your code. @Marius Espejo . Great video

  • @germanwibaux6923
    @germanwibaux6923 2 ปีที่แล้ว

    it gives me this error "Error: Unknown authentication strategy "local"". I can't found the solution yet. Bye!

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว +1

      That likely means you didn’t register the strategy in any module

  • @josegonzalez-jg1kj
    @josegonzalez-jg1kj 2 ปีที่แล้ว

    But, how it would be for email, password? because, i am triying to use passport local strategy for email, password and not working

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      You can configure the local strategy to use a different field e.g. email instead of username

  • @ivanmilovac9482
    @ivanmilovac9482 2 ปีที่แล้ว

    Hi Marius, should we pass super() in constructor of JwtAuthGuard (th-cam.com/video/_L225zpUK0M/w-d-xo.html) ?

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      If you’re explicitly defining the constructor I believe so yes

  • @asogbaibrahim9618
    @asogbaibrahim9618 ปีที่แล้ว +1

    I love this tutorial. Clear as Spring water 💯

  • @mohabedr5030
    @mohabedr5030 3 หลายเดือนก่อน

    bro with this approach the user need to register and then login, we should be able to register and automatically login

    • @mariusespejo
      @mariusespejo  3 หลายเดือนก่อน

      So create a jwt at register, nothing stopping you from achieving that

  • @JawwadNissar
    @JawwadNissar ปีที่แล้ว

    you did amazing job. plz tell one thing. how to implement authentication on microservice based architecture

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      That’s a bit of a loaded question that is not simple to answer in a comment. First of all there are several strategies that depends a lot on your infrastructure, your identity provider, etc. Next the “how” again will depend on the strategy. I suggest spending some time reading about it

  • @johnparungao1354
    @johnparungao1354 ปีที่แล้ว

    What are the reasons you chose React over Angular? knowing nestjs is literally angular but backend ?

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      pick tools based on what you believe is best for the task, not based on similarities.

  • @bjfviheoiv
    @bjfviheoiv 2 ปีที่แล้ว

    can i change the serializer service anme to CookieSerializer ? how passport know where to look for this functions of serial/deserial ?

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Im not sure that the name matters as long as it is extending PassportSerializer and that you’re registering it as a provider, Nest automatically calls it by convention when you’re using sessions with passport

  • @bigg565
    @bigg565 ปีที่แล้ว

    Hi, first of Your video is great and I think I understand whats going on, but the thing is i keep getting an error. I followed everything like You, but now I get inside my terminal [Nest] 15540 - 25.02.2023, 18:21:59 ERROR [ExceptionsHandler] Unknown authentication strategy "local"
    Error: Unknown authentication strategy "local"
    and after I use postman I get 500 internal server error as an result. Do You have any idea how to fix this? I really dont know what to do. Thanks :)

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      Likely means you didn’t register your strategy in the providers in the AuthModule

    • @bigg565
      @bigg565 ปีที่แล้ว

      @@mariusespejo I did, at least I have LocalStrategy inside my providers array, any other ideas?

  • @e.magnoneto5101
    @e.magnoneto5101 11 หลายเดือนก่อน

    Hiiii, i´m super excited to learn more about nest.js, is a such framework. May u can give me one tip, how do i use this session savinf user, and jwt at redis in a graphql API, is the same process? what i need change to works? thank u soo much for that incredible channel, i also follow u in linkendin. Bye

    • @mariusespejo
      @mariusespejo  11 หลายเดือนก่อน +1

      Thanks! I do have a nestjs graphql auth video I think in the channel

    • @e.magnoneto5101
      @e.magnoneto5101 11 หลายเดือนก่อน

      @@mariusespejo ok, i will see it

  • @josipkes
    @josipkes 6 หลายเดือนก่อน

    Extremely valuable content, thanks.

  • @ali-d-coded5620
    @ali-d-coded5620 ปีที่แล้ว

    you should make a video on serving html in nestjs like to create a dashboard html/htmx

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      Yeah could be a good video idea, htmx has been on my radar

  • @h.w.b.9503
    @h.w.b.9503 ปีที่แล้ว +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

  • @wakibtz7134
    @wakibtz7134 ปีที่แล้ว

    how can i take a user information on client if i make session based auth? I get session id in cookie but what i can make with it

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว +1

      You can expose an endpoint to get users details like GET /current-user
      The cookie basically is a key to that, assuming the user has logged in
      Plus any request your client sends with that cookie, your backend will know was being invoked as that user

  • @mochamadrasyad338
    @mochamadrasyad338 ปีที่แล้ว

    Awesome !! 🔥🔥, Thank you very much

  • @darpananeja6755
    @darpananeja6755 2 ปีที่แล้ว +1

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

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว +1

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

  • @quamzgraphix9826
    @quamzgraphix9826 ปีที่แล้ว +1

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

  • @axelle9764
    @axelle9764 6 หลายเดือนก่อน

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

  • @pronaxking1918
    @pronaxking1918 ปีที่แล้ว

    What if I have multiple strategy.ts files for the same Strategy for passport. How would i let Passport know which file to use when!

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      You use the decorators on a per-route basis

    • @pronaxking1918
      @pronaxking1918 ปีที่แล้ว

      @@mariusespejo okay got it! Thanks a lot!!

  • @mickomagallanes1185
    @mickomagallanes1185 ปีที่แล้ว

    Thank you Marius, building a NestJS Login with MikroORM alone is a huge pain for me, is it possible to get the source code of this tutorial?

  • @dalmiro2h
    @dalmiro2h 7 หลายเดือนก่อน

    this a have a circular dependency dont?

  • @LeahLaposta
    @LeahLaposta 2 ปีที่แล้ว

    When I enter
    @Post('login')
    login(@Request() req): any {
    return req.user;
    }
    I get this warning:
    Value of type '{ new (input: RequestInfo, init?: RequestInit): Request; prototype: Request; }' is not callable. Did you mean to include 'new'?
    Any idea where I may have gone wrong? using quick fix to add 'new' to Request just gave another error.

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Double check you’re importing Request from the correct path, sounds like you’re not

    • @LeahLaposta
      @LeahLaposta 2 ปีที่แล้ว

      @@mariusespejo Thank you, I will try that! Is your code for this project on a github repo? I'm not able to see where I should import Request from and your github isn't linked in your description.

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      Not for this one sorry. You should be able to see where I’m importing from on the video right? Make sure it’s from nest and not the type from express

  • @profx53
    @profx53 ปีที่แล้ว

    Hi, will you add this code to the github?

  • @kushagrasrivastava2127
    @kushagrasrivastava2127 2 ปีที่แล้ว

    can you share github link brother??

  • @divineenergy2900
    @divineenergy2900 2 ปีที่แล้ว

    41:40 request.isAuthenticated(); getting undefined function

    • @mariusespejo
      @mariusespejo  2 ปีที่แล้ว

      That likely means you didn’t set up the local strategy and it’s guard correctly

  • @tukuyoma
    @tukuyoma 2 ปีที่แล้ว +1

    Great video

  • @vulezor
    @vulezor ปีที่แล้ว

    Oh man, you should use the database the whole trick is within that.

    • @mariusespejo
      @mariusespejo  ปีที่แล้ว

      Database is just storage, not required to talk about auth

  • @MisaoM
    @MisaoM 2 ปีที่แล้ว +1

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

  • @shashankmarri1056
    @shashankmarri1056 2 ปีที่แล้ว

    Do you have a this code in GitHub?