Тёмный

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

Marius Espejo
Подписаться 29 тыс.
Просмотров 165 тыс.
50% 1

Опубликовано:

 

28 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 423   
@mariusespejo
@mariusespejo 2 года назад
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 года назад
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 ;-)
@sailormetz7148
@sailormetz7148 2 года назад
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 Год назад
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 RU-vid. 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
@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 🙏
@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!!
@МихаилЧон
@МихаилЧон 3 года назад
You are gonna be famous soon
@Bingo901
@Bingo901 Год назад
When
@mariusespejo
@mariusespejo Год назад
Never lol
@JamesBower
@JamesBower 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.
@bossmusa9075
@bossmusa9075 Год назад
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.
@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!
@thecastiel69
@thecastiel69 3 года назад
This tutorial I wanted today, what a coincidence
@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!
@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!
@DevNiklesh
@DevNiklesh 3 года назад
Best Nest.js content on YT so far.. Keep up the good work man @Marius
@mariusespejo
@mariusespejo 3 года назад
thanks Dev! glad you like the content
@musbell
@musbell 3 года назад
Thanks, @Marius! The video is so helpful, I really learnt a lot.
@zenith.mg777
@zenith.mg777 Год назад
Great video! It helps me a lot, thank you!
@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
@hasst9261
@hasst9261 5 месяцев назад
Cool content Rly helpful Ty!
@devbel
@devbel Год назад
Great one 👌 Thanks
@warsisarjeelrahman3940
@warsisarjeelrahman3940 3 года назад
Can you please make a complete authentication tutorial with nestjs and react? Love the nest videos.
@mariusespejo
@mariusespejo 3 года назад
will definitely consider it!
@kunheelim881
@kunheelim881 3 года назад
@@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.
@maxbraun6271
@maxbraun6271 Год назад
Great video thank you!
@jaumoso23
@jaumoso23 Год назад
Thank you so much for this tutorial
@argya2073
@argya2073 10 месяцев назад
thank you marius, your are awesome
@bozabonilla
@bozabonilla 3 года назад
I looking for this same but with graphql, good video my friend, it will help me
@bgabriel7581
@bgabriel7581 3 года назад
Thanks for your video, i loved!!!
@vanshdubey21
@vanshdubey21 4 месяца назад
VERY VERY HELPFUL VIDEO
@adeyemisunday6866
@adeyemisunday6866 2 года назад
Marius the Genius....#Legend
@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 года назад
fyi just published a new video specifically on that topic!
@alesofton
@alesofton 2 года назад
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
@MultiShokk69
@MultiShokk69 2 года назад
Awesome tutorial like always thank you, If you can do some new tutorial in vuejs / nestjs it will be awesome
@thongtech1984
@thongtech1984 2 года назад
Yes, another awesome awesome videos,
@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 года назад
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
@malinduupendra7117
@malinduupendra7117 2 года назад
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
@MahmoudAhmed-nq7ou
@MahmoudAhmed-nq7ou 8 месяцев назад
(this.validate is not a function) this error had shown to me can someone help me please
@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!
@mariusespejo
@mariusespejo 3 года назад
Thank you! 🙏
@swapnilcodes
@swapnilcodes 2 года назад
Awesome !
@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
@elrenzo
@elrenzo 3 года назад
Amazing , thanks 😀
@shashankmarri1056
@shashankmarri1056 2 года назад
Do you have a this code in GitHub?
@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
@IanGem1121
@IanGem1121 3 года назад
I've been looking for this. Can you do a video on nestjs database provider with mongoose?
@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
@JuanVqz
@JuanVqz 3 года назад
I used to do backend things on ruby on rails, when we want to update something we use PUT/UPDATE verb which is pointed up to the update method, how do you do that where if the method it's tied with the verb decorator? or is it possible to do something like this @put("users") @patch("users") in the same place? thank you for your content
@mariusespejo
@mariusespejo 3 года назад
I’m not sure that you can do both verbs in one like that, however assuming the bulk of your business logic is on the service/provider then it’s not much more code to add an extra method on the controller class and just reuse the same service method
@OmAr-vv6fh
@OmAr-vv6fh 3 года назад
Thank you for this video Marius. Would you be able to share what theme and font you're using?
@mariusespejo
@mariusespejo 3 года назад
I believe this one is the Night Owl. Not using any special font, it’s just the default
@OmAr-vv6fh
@OmAr-vv6fh 3 года назад
@@mariusespejo thank you
@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
@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.
@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 года назад
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!
@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
@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 Год назад
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 Год назад
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
@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
@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!
@vinaykaithwas2973
@vinaykaithwas2973 2 года назад
29:09 Session
@mariusespejo
@mariusespejo 2 года назад
There are timestamps in the description if you need it
@veselinmadzhirov2211
@veselinmadzhirov2211 2 года назад
Great tutorial! How can i have the code base? Github? Thanks is advance! Keep up the great work.
@veselinmadzhirov2211
@veselinmadzhirov2211 2 года назад
@Marius Espejo
@mariusespejo
@mariusespejo 2 года назад
It’s not in a repo at the moment sorry
@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 года назад
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
@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
@mynameisjeff8559
@mynameisjeff8559 Год назад
BEST VIDEO
@goodcoder4953
@goodcoder4953 2 года назад
🙏 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
@jessicamaria682
@jessicamaria682 3 года назад
Thank you for this video!
@mariusespejo
@mariusespejo 3 года назад
No problem 😄
@nomanahmedkhan6352
@nomanahmedkhan6352 Год назад
can u share this source code,?
@andriancabisada4313
@andriancabisada4313 2 года назад
github repo please. haha
@mariusespejo
@mariusespejo 3 года назад
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.
@kinopiskfreepromocode5546
@kinopiskfreepromocode5546 2 года назад
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
@kurtestacion6113
@kurtestacion6113 3 года назад
Can you do more of nestjs with graphql like auth and/or microservices. That would be a unique content!
@mariusespejo
@mariusespejo 3 года назад
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 года назад
hey folks, just following up: new video just posted on doing this same auth topic but in graphQL specifically
@manishupadhyay4519
@manishupadhyay4519 3 года назад
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 года назад
Can't thank you enough for this Marius, excellent content, pitched and paced perfectly.
@mariusespejo
@mariusespejo 2 года назад
Thank you! I appreciate the feedback
@FunkyToe369
@FunkyToe369 3 года назад
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
@santiagazolara
@santiagazolara 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 года назад
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.
@OetziOfficial
@OetziOfficial 3 года назад
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 года назад
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 года назад
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
@batuhanbag5054
@batuhanbag5054 2 года назад
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 года назад
Thank you!!!!....You saved my time
@batuhanbag5054
@batuhanbag5054 2 года назад
@@satyamprajapati3779 You’re welcome happy coding !
@usmanakram5458
@usmanakram5458 2 года назад
Such a masterpiece bro♥️ everything is perfect in this video 🏳️🙌
@ash1982ok
@ash1982ok 3 года назад
could you please share your source code?
@xZunaii
@xZunaii 2 года назад
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!
@akarihinata8975
@akarihinata8975 2 года назад
Is it possible to login just after signup (register) ?
@mariusespejo
@mariusespejo 2 года назад
Yeah don’t see why not
@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??
@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!
@saikatjaman2004
@saikatjaman2004 3 года назад
Hi Sir, Thanks for the osm Tutorial, can we have the git link for source code plz.
@lakeman4101
@lakeman4101 2 года назад
it would have been great to have your git hub repo to the project to interact well with your code. @Marius Espejo . Great video
@muhammadharis2205
@muhammadharis2205 Год назад
req.isAuthenticated gives error ""request.isAuthenticated is not a function" at 29.02 section.
@h.w.b.9503
@h.w.b.9503 Год назад
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
@asogbaibrahim9618
@asogbaibrahim9618 Год назад
I love this tutorial. Clear as Spring water 💯
@tunghaotu8652
@tunghaotu8652 2 года назад
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 года назад
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
@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)
@tukuyoma
@tukuyoma 2 года назад
Great video
@mariusespejo
@mariusespejo 2 года назад
Thank you!
@Thilina4321
@Thilina4321 3 года назад
Thank you very much
@quamzgraphix9826
@quamzgraphix9826 Год назад
your nest js contents are soo good. keep it up marius
@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
@josipkes
@josipkes 6 месяцев назад
Extremely valuable content, thanks.
@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?
@mochamadrasyad338
@mochamadrasyad338 Год назад
Awesome !! 🔥🔥, Thank you very much
@dalmiro2h
@dalmiro2h 7 месяцев назад
this a have a circular dependency dont?
@kushagrasrivastava2127
@kushagrasrivastava2127 2 года назад
can you share github link brother??
@profx53
@profx53 Год назад
Hi, will you add this code to the github?
@ivanmilovac9482
@ivanmilovac9482 2 года назад
Hi Marius, should we pass super() in constructor of JwtAuthGuard (ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-_L225zpUK0M.html) ?
@mariusespejo
@mariusespejo 2 года назад
If you’re explicitly defining the constructor I believe so yes
@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
@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
@germanwibaux6923
@germanwibaux6923 2 года назад
it gives me this error "Error: Unknown authentication strategy "local"". I can't found the solution yet. Bye!
@mariusespejo
@mariusespejo 2 года назад
That likely means you didn’t register the strategy in any module
@darpananeja6755
@darpananeja6755 2 года назад
So glad to know that you are following the official NestJs documentation! I also do the same.
@mariusespejo
@mariusespejo 2 года назад
Honestly it’s some of the best docs I’ve seen!
@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
@im_rihan
@im_rihan 2 года назад
can u give me this course github link
@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
@faez322
@faez322 3 года назад
Awesome, please continue ;)
@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.
Далее
Session Vs JWT: The Differences You May Not Know!
7:00
ОБЗОР НА ШТАНЫ от БЕЗДNA
00:59
Просмотров 187 тыс.
Being Competent With Coding Is More Fun
11:13
Просмотров 81 тыс.
Decouple your NestJS code with this technique!
11:37
Просмотров 38 тыс.
The ultimate NestJS Authentication guide
31:00
Просмотров 9 тыс.
NestJS Authentication + Refresh Token With Passport.js
1:25:12