Also note that this is a complex topic and you must do some read before jumping into implementing it. A few things to keep in mind: Anything that you put in a JWT is signed, but not encrypted, so anyone can read the user details that you attach to it. Don't expose anything sensible. Usually the JWT approach also involves returning a "refresh token" along the access token. The access one is short lived and the refresh one is long lived. The client then uses the refresh one to exchange it for another access token when this is about to expire. This is in order to minimize the damage that someone could do by stealing an access token. Finally bear in mind that there are other signing algorithms besides a shared secret (HMAC). The current state of the art if I'm not wrong is EdDSA / Ed25519 which uses a set of private and public key to sign and verify respectively. Cheers!
Generally you’d need to store something server side which uniquely identifies any given jwt, or actually just store sessions in a shared store like redis or similar and use the jwt (or a value within it) as the key to the record. Then revoking in either case is simply removing that corresponding server-side record, and making sure to always check that it exists to determine if the jwt is still valid (in addition to the other typical verification)
You made me subscribe to your channel~ I like your contents about NestJS because I'm a fan of it also. And also, I'm planning to create contents with it soon when there are available time. Clear, detailed, and an audible voice. More power!
Great vid Marius! You're right this topic is usually not well documented and I had a hard time trying to find a nice tutorial / article, I like the way you explain all concepts in detail you helped me a lot Cheers!
Seriously, buddy, you nailed it. I really enjoyed your deep dive into this topic, where you performed each and every step while also explaining each and every step. Thank you so much for your excellent teaching and knowledge sharing, and I hope and pray that your channel will continue to expand... Thank you very much once again.
I know you mentioned that you're not giving us the 'production-ready' solution, would you ever consider going into things like best practices for production-ready apps? Without hands-on industry experience it's difficult to get out of the RUclips/Udemy to-do apps level of work. Love the content by the way - miles ahead of other RUclipsrs!
production-readiness really depends a lot on several things: your or your company’s infrastructure, your security and privacy requirements, etc. It’s a big topic that can go in several different paths. With that said I don’t claim to know all possible or best paths but I’d definitely like to cover more systems design stuff which might cover some of it. Anyways thanks for your input and feedback!
nestjs+graphql is a topic that I feel isn't covered by many people, I do appreciate this tutorial. Do you have any plans to cover how nest deals with federated gql services?
i want to forgot and reset password authentication nestjs + graphql but i didn't see any videos can you suggest me any videos or tutoial which help me and if you make video so well good
Yup don’t think I covered it here but definitely good to consider having a refresh flow, e.g. creating a refresh token alongside the access token, that way when it expires you can refresh and get a new one using the refresh token, allowing the user to not have to login again. You have to be smart however with making sure that it’s stored securely and also is rotated. A compromised refresh token would be pretty bad
great! would be cool to have a new tutorial where apollo federation v2 is also in the scenario and calls to a secure gateway provides auth for other services in comm with auth service.
Hello, thank you very much for another incredibly educational video. I had seen the session video and was thinking about how to develop a secure API to be put into production. Could you tell me if I'm exaggerating because I would like to put sessions id in cookies, these sessions are stored in a cache database like redis, and within this session, we have the user and the jwt. Or would just sessions be safer?
Furthemore errors like: "Missing conditions" from auth files from passport package = explanation in: 13:30 video. Remember to add "@Injectable" to 'LocalStrategy' class Remember to add "@Column" to entity (without saving to db work, but when You retrieve data from db those will miss :D
Thx for the tutorial Marius, always looking forward to your next videos. I have a question concerning securing the user, you didn't create a password field in the user entity, but wouldn't that create a problem when validating the user since findOne() will return a User and you'll have to compare his password, yet it isn't defined in the User entity, so that would normally return an error, I'm confused why my code addressed that error yet your code didn't.
Thanks for calling that out, I had to double check what I did in the video. You are correct that the entity should have a password field that I think I forgot to add in the video or accidentally edited it out, although if you watch the rest of the video I do create an array of users (my fake database) which includes a password field
Hi thank you so much for making this video! I have a question I'd like to ask. In your example, there is one type of user to be validated. If an application has more than one type of users to validate, and they have different graphql database schema, how should I implement the authentication so it's scalable?
The validation part is totally up to you. If you have multiple types of users then your validation should account for that, e.g. perhaps your query helps determine what type of user it is
Hi @@mariusespejo thanks for the reply. What I was wondering was about the auth resolver query that validate the username/email. In the case of having one type of user, the validate query should return a promise of that user type and there is no confusion in that. However, when I have two or more classes of users that have different schema, do I need to define multiple of the validate queries, each returning a promise of the corresponding user class? Or, is there a more elegant way to handle all of the validation and login queries? I am quite new to NestJS and passport.js and not sure what the standard practice for this case is. Thanks!
When playing with JwtStrategy make sure to import 'Strategy' class from 'passport-jwt' instead of 'passport-local', it will lead to error 'unknown auth method 'jwt' '. I got this issue when was auto-importing files via vsc.
Mutations aren’t necessarily just for writing data, it can also be for things which changes state. That includes things like user sessions, login activity etc. you’re not simply fetching data in most cases with auth, you’re mutating the server’s state. For simpler state-less situations yeah I could see it being just a query
@@mariusespejo Thanks for your response. One more question can we send own error messages for wrong arguments(Boolean type for string types) instead of deafult graphql error messages
Well checking that it matches the expect schema is one of the things graphql is designed to do, but beyond that if you have other custom validation yeah you definitely can customize the response
Great videos, Marius! but I'm having hard time combining auth & authz. I followed your previous auth & casl videos and combined them but got a error "user undefined - in the ability factory" and unexpected behaviors when using jwt and casl guards together in one resolver endpoint. We definitely need your help. Please, make a tutorial jwt + casl + actual db(typeorm sqlite). Thanks buddy!
Great, thanks for your video, but it would make it easier if you can provide the source code. Sometimes, I had unusual bug and could not make the comparison with your library version. Anw, thanks for your content.
What's the point of using passport and passport strategies? It looks like it gives overhead only. Why not just make a regular login mutation which accepts username and password, checks it against bcrypt, and then generates and returns jwt? And then just make a regular middleware which extracts bearer token, checks it and adds user to the context. And then something like graphql-shield might be used for permissions. All these steps you already completed in this great tutorial. I just don't understand how passport works and helps in any way here.
You absolutely could that. Where passport shines is that it helps keep implementations across multiple projects mostly consistent. Also strategies are swappable, if one day you decide to change auth strategies, e.g. maybe you want to do it via a 3rd party service or perhaps oauth, oidc, etc… then you just change strategies, the rest of the functionality stays the same. This one with basic user/password is honestly the simplest strategy so it’s not as easy to see the value. However other strategies are much more complex to put together from scratch
Very clear and easy to follow along, thank you. Default algorithm is HS256 as far as I saw. How to generate a JWT for HS512? A sample would be of the highest appreciation 😀
The nestjs/jwt package is really just using the jsonwebtoken package underneath, and the sign method takes in an option object that allows to set the algorithm, see: github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback
I actually have been trying both ways, you’ll notice in my teamseas video I used schema first which I thought made it a little more consistent with prisma. This really just goes down to preference but in NestJS specifically I think code-first is actually better, because you can fully utilize decorators e.g. setting up class-validator with input types
You don’t have to think about it as something you need to “combine” they can and should likely be be two different deployments. Your react client would make API requests to your nest backend. Now if you really want to combine them, you NestJs server can also serve static content: docs.nestjs.com/recipes/serve-static
@@mariusespejo yes i have watched but i am working on authentication and when i am validate user password i have some issues, my password bcrypt on database
Does anyone have a good idea/example how to combine NestJS, GraphQL and session authorization using passport? I am thinking of something like this: ruclips.net/video/_L225zpUK0M/видео.html
Not sure if you watched this whole video but I did cover using the same passport-local strategy here and how to get that to work with graphql. Copy the way sessions are created in that other video and you’re basically there
this isn't really meant for interview prep but good luck on your interviews man! If it feels like too much for you spend some time reading about the topic, it's important to understand the fundamentals... most of what I'm showing here is just a single implementation
Also note that this is a complex topic and you must do some read before jumping into implementing it.
A few things to keep in mind:
Anything that you put in a JWT is signed, but not encrypted, so anyone can read the user details that you attach to it. Don't expose anything sensible.
Usually the JWT approach also involves returning a "refresh token" along the access token. The access one is short lived and the refresh one is long lived. The client then uses the refresh one to exchange it for another access token when this is about to expire. This is in order to minimize the damage that someone could do by stealing an access token.
Finally bear in mind that there are other signing algorithms besides a shared secret (HMAC). The current state of the art if I'm not wrong is EdDSA / Ed25519 which uses a set of private and public key to sign and verify respectively.
Cheers!
great points!
How does one revoke a JWT?
Generally you’d need to store something server side which uniquely identifies any given jwt, or actually just store sessions in a shared store like redis or similar and use the jwt (or a value within it) as the key to the record. Then revoking in either case is simply removing that corresponding server-side record, and making sure to always check that it exists to determine if the jwt is still valid (in addition to the other typical verification)
@@mariusespejo Any chance you can follow up and show this implemented with a refresh token as well?
I’d love a follow up with refresh token as well, as that is something one really would need.
This saved me a day. Now, I can implement Jwt Strategy with GraphQL in NestJS. Thanks a lot for your video :))
Learn GraphQl using NestJS based on this tutorial. Thaks Marius keep going on...
You made me subscribe to your channel~ I like your contents about NestJS because I'm a fan of it also. And also, I'm planning to create contents with it soon when there are available time. Clear, detailed, and an audible voice. More power!
Thank you! Yeah if you’re at all interested in creating content, I highly recommend it. Great way to learn
Great vid Marius! You're right this topic is usually not well documented and I had a hard time trying to find a nice tutorial / article, I like the way you explain all concepts in detail you helped me a lot
Cheers!
Seriously, buddy, you nailed it. I really enjoyed your deep dive into this topic, where you performed each and every step while also explaining each and every step. Thank you so much for your excellent teaching and knowledge sharing, and I hope and pray that your channel will continue to expand... Thank you very much once again.
Thanks for your support Raj! I appreciate the feedback 🙏
Thank you very much for your video! Literally the best nestjs videos existing!
thanks for these effective tutorials. we expect more like these. thanks a lot.
Just in time man, I needed. Thanks man 🤞
I know you mentioned that you're not giving us the 'production-ready' solution, would you ever consider going into things like best practices for production-ready apps? Without hands-on industry experience it's difficult to get out of the RUclips/Udemy to-do apps level of work. Love the content by the way - miles ahead of other RUclipsrs!
production-readiness really depends a lot on several things: your or your company’s infrastructure, your security and privacy requirements, etc. It’s a big topic that can go in several different paths. With that said I don’t claim to know all possible or best paths but I’d definitely like to cover more systems design stuff which might cover some of it.
Anyways thanks for your input and feedback!
Thanks. Really instructive
That was really awesome yo. Enjoyed
thank you, bro. Amazing tutorial!!!
Right when i need it again! I think you can read minds Marius!
Thanks for this concise tutorial
Thanks, this helps me alot!
nestjs+graphql is a topic that I feel isn't covered by many people, I do appreciate this tutorial. Do you have any plans to cover how nest deals with federated gql services?
Look at Krishna NestJS. He does a great job explaining federation in with graphql and nest.
Will probably cover it at some point, still figuring out the overall content strategy for the channel. Thanks for the idea!
28:50 => 30:00 Spoiler: The user in context has already had its password stripped, so there's no need to do it again at line 23 in login.
i want to forgot and reset password authentication nestjs + graphql but i didn't see any videos can you suggest me any videos or tutoial which help me and if you make video so well good
Hey mentor, quick question: What are your thoughts about refreshing the token? It's crucial for security and user experience.
Yup don’t think I covered it here but definitely good to consider having a refresh flow, e.g. creating a refresh token alongside the access token, that way when it expires you can refresh and get a new one using the refresh token, allowing the user to not have to login again. You have to be smart however with making sure that it’s stored securely and also is rotated. A compromised refresh token would be pretty bad
Bro amazing video, thanks a lot
you’re welcome!
great! would be cool to have a new tutorial where apollo federation v2 is also in the scenario and calls to a secure gateway provides auth for other services in comm with auth service.
Hello, thank you very much for another incredibly educational video.
I had seen the session video and was thinking about how to develop a secure API to be put into production. Could you tell me if I'm exaggerating because I would like to put sessions id in cookies, these sessions are stored in a cache database like redis, and within this session, we have the user and the jwt. Or would just sessions be safer?
Awesome!
Furthemore errors like:
"Missing conditions" from auth files from passport package = explanation in: 13:30 video.
Remember to add "@Injectable" to 'LocalStrategy' class
Remember to add "@Column" to entity (without saving to db work, but when You retrieve data from db those will miss :D
Thx for the tutorial Marius, always looking forward to your next videos. I have a question concerning securing the user, you didn't create a password field in the user entity, but wouldn't that create a problem when validating the user since findOne() will return a User and you'll have to compare his password, yet it isn't defined in the User entity, so that would normally return an error, I'm confused why my code addressed that error yet your code didn't.
Thanks for calling that out, I had to double check what I did in the video. You are correct that the entity should have a password field that I think I forgot to add in the video or accidentally edited it out, although if you watch the rest of the video I do create an array of users (my fake database) which includes a password field
can you do a tutorial on how to deploy nestjs application to digital aceans for example
Will consider it
Hi thank you so much for making this video! I have a question I'd like to ask. In your example, there is one type of user to be validated. If an application has more than one type of users to validate, and they have different graphql database schema, how should I implement the authentication so it's scalable?
The validation part is totally up to you. If you have multiple types of users then your validation should account for that, e.g. perhaps your query helps determine what type of user it is
Hi @@mariusespejo thanks for the reply. What I was wondering was about the auth resolver query that validate the username/email. In the case of having one type of user, the validate query should return a promise of that user type and there is no confusion in that. However, when I have two or more classes of users that have different schema, do I need to define multiple of the validate queries, each returning a promise of the corresponding user class? Or, is there a more elegant way to handle all of the validation and login queries? I am quite new to NestJS and passport.js and not sure what the standard practice for this case is. Thanks!
It would be nice if we had the sources for this example.
What is the name of your font?
When playing with JwtStrategy make sure to import 'Strategy' class from 'passport-jwt' instead of 'passport-local', it will lead to error 'unknown auth method 'jwt' '.
I got this issue when was auto-importing files via vsc.
Yep! Easy to mix up
Very nice! Please more nestjs+graphql, medium/amazon clone?
Yeah! Will consider it
How could I integrate roles within this approach?
Like authorization? You can take a look at my videos about CASL
@@mariusespejo Yes, oh I'll take a look thank you!
Why we are using mutation instead of query for login method? We are not writing any data right ?
Mutations aren’t necessarily just for writing data, it can also be for things which changes state. That includes things like user sessions, login activity etc. you’re not simply fetching data in most cases with auth, you’re mutating the server’s state. For simpler state-less situations yeah I could see it being just a query
@@mariusespejo Thanks for your response.
One more question can we send own error messages for wrong arguments(Boolean type for string types) instead of deafult graphql error messages
Well checking that it matches the expect schema is one of the things graphql is designed to do, but beyond that if you have other custom validation yeah you definitely can customize the response
The way you replying to each mesgae is ♥️.
One request can you make a series on micro services from basic to advance level ☺️
Well I try to respond when I can 🙂 I’ll think of how I might do something like that, thanks for the idea!
Do I need to give the user an access token after registration?
Depends on if you log the user in automatically after registration. If you ask them to login explicitly the first time then I assume no
Great videos, Marius! but I'm having hard time combining auth & authz. I followed your previous auth & casl videos and combined them but got a error "user undefined - in the ability factory" and unexpected behaviors when using jwt and casl guards together in one resolver endpoint. We definitely need your help. Please, make a tutorial jwt + casl + actual db(typeorm sqlite). Thanks buddy!
Hello, can you share the github repo of this video.
Great, thanks for your video, but it would make it easier if you can provide the source code. Sometimes, I had unusual bug and could not make the comparison with your library version. Anw, thanks for your content.
That’s a good point, thanks for the feedback. Will try to find some time to get most of the code from my videos in a repo
Can you do a video on Wundergraph? Looks awesome.
Maybe when it goes open source
What's the point of using passport and passport strategies? It looks like it gives overhead only. Why not just make a regular login mutation which accepts username and password, checks it against bcrypt, and then generates and returns jwt? And then just make a regular middleware which extracts bearer token, checks it and adds user to the context. And then something like graphql-shield might be used for permissions. All these steps you already completed in this great tutorial. I just don't understand how passport works and helps in any way here.
You absolutely could that. Where passport shines is that it helps keep implementations across multiple projects mostly consistent. Also strategies are swappable, if one day you decide to change auth strategies, e.g. maybe you want to do it via a 3rd party service or perhaps oauth, oidc, etc… then you just change strategies, the rest of the functionality stays the same. This one with basic user/password is honestly the simplest strategy so it’s not as easy to see the value. However other strategies are much more complex to put together from scratch
code link available?
Very clear and easy to follow along, thank you. Default algorithm is HS256 as far as I saw. How to generate a JWT for HS512? A sample would be of the highest appreciation 😀
The nestjs/jwt package is really just using the jsonwebtoken package underneath, and the sign method takes in an option object that allows to set the algorithm, see: github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback
Can you make some RemixJS videos?
Yeah! Im actually probably going to look into that soon
Great video but why code first?! The schema is so much easier to write out!
I actually have been trying both ways, you’ll notice in my teamseas video I used schema first which I thought made it a little more consistent with prisma. This really just goes down to preference but in NestJS specifically I think code-first is actually better, because you can fully utilize decorators e.g. setting up class-validator with input types
@@mariusespejo that all are very good reasons, Thanks!
I wish you would create a crash course about react.js and nest.js
I do have one for nest.. It doesn’t really make sense to do them together, nest is agnostic to whatever your frontend is
@@mariusespejo thanks , yes but I don't know how to combine these together and how to deploy them
You don’t have to think about it as something you need to “combine” they can and should likely be be two different deployments. Your react client would make API requests to your nest backend.
Now if you really want to combine them, you NestJs server can also serve static content: docs.nestjs.com/recipes/serve-static
THANK YOUUUUU
you’re welcome!
please make a video on nest js graphql file uploading🙏
nice tutorial but please make video also with database postgres
What are you looking for with postgres? I have videos on the channel with prisma and typeorm, they both expose an api that’s mostly database agnostic
@@mariusespejo yes i have watched but i am working on authentication and when i am validate user password i have some issues, my password bcrypt on database
Where's the github repo?
Great content, where Can I donate you?
I don’t have a place for that at the moment but thank you for the thought 🙏
@@mariusespejo Make it or just start selling your knowledge somewhere. It's fresh, new-standard and properly explained.
Hi! Thanks!
Please add link on source codes in description!
plz, give me repo
Does anyone have a good idea/example how to combine NestJS, GraphQL and session authorization using passport? I am thinking of something like this: ruclips.net/video/_L225zpUK0M/видео.html
Not sure if you watched this whole video but I did cover using the same passport-local strategy here and how to get that to work with graphql. Copy the way sessions are created in that other video and you’re basically there
dude chill youre too fast there are beginners watching this to pass interviews
this isn't really meant for interview prep but good luck on your interviews man! If it feels like too much for you spend some time reading about the topic, it's important to understand the fundamentals... most of what I'm showing here is just a single implementation