NestJS: JWT Generation & JwtAuthGuard | NestJS Auth with JWT & Password Hashing Series 3/4

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi and welcome back to the third video of a nesgas authentication with jwt and passport hashing series in this video we are very simply covering how to generate betray wt how to sign it with a secret and with expiration date for example and then we add also wt guard and with a strategy so that for example if you log in you will get a return the jwt token which contains in a payload for example your user properties your name your email whatever you need and then we have another endpoint which is then protected by a jwt guard which checks if there's the valid readability on the request or not and if it is there then it will apply the payload to our request and it's all okay but if you don't you know give him like a valetrawt token for this service of our api then your access is denied or you are unauthorized so let's have a look at the structure of this video at first we look at the outcome of this video then we will read the user story for it and then we will implement it and close it so let's have a quick look to the outcome of this video so you can see here we still have our request where we get all the users and where we want to log in and before we could access this without a jwt but now we have a tradability of guard in our application for this endpoint here so we need to give him a valid jwt otherwise our request will get an error response so you see we are not authorized to do something or to get the users so we need a valid jwt attached and this we can get if we log in with our email and password when we get in response we access token we token type and the expires in and then we have to copy and paste our token and say we want to make this request here with bearer token and add this token and then we can make a simple get request and we get in return all the users because now we are having a valid trade wt that is signed correctly and is not expired so here we are still in our sjs of jwt series and the last time we added the red resistor and log in routes and hash the password and also validated all the requests of the incoming requests if everything is correct so now we are having story free where we want to add the jwt generation with login so the story is as a user i want to be authenticated via a jwt token so if i make a request against the api i am authenticated by vray wt token so here we want that if i hit v login route and then as before we use all the stuff where we compare or look up the email the user compare the password with the password hash that's stored in the database and at the moment we are just sending to our client everything login was correct successful but now we want to generate a jwt token so that for other requests we can use the straightawt token in the client to validate us against our backend but i'm actually the user that i am so we have here some acceptance criteria so first we want an over or to give an overview over jwt and the implementation in sjs so we then go above the documentation here from nestges and from jwtio and we want to install all needed packages we want to add a function where we generate withdraw wt to our authentication service we want to add an import to our gw team or we want to add the import of our jwt module to our imports array from our auth module so we and there we can specify what secret do we want to use and so on we want to add our jwt guard and our trade level 2 strategy we will go deeper in this here in the first point where we look over the implementation in s3s why we need those guards and solid trees then we want to generate a trader but in our login function so right now we're just making a string or returning a string but actually we want to return then the generate jwt we want to add a find one function to our user service because at the moment we are just having defined by email and this is configured that it also returns the password but we don't want to add like the password to the user proper or to the user object that we want to return after logging in or add to our jwt token and at last we want to implement our jwt guard on our end point where we get all the users so because on the register endpoint we don't want the guard because everyone should be able to register and all of the endpoint we can't have a guard because um you first have to log in to a jwt token but on our end point where we get all the users we can verify that you can only query this endpoint if you're having a valid jwt token and only then you will get a response otherwise you will get an error or an error response so we can now move this to doing here and first we want to have a look above or about the jwt token and then about the implementation industries so you can always go to the jwtio page and here you have an introduction to json web tokens so what is a json web token it's an open standard that defines a compact and self-contained way for securely transmitting information between parties as a json object so it is can be verified and trusted because it is digitally signed and they can be signed using a secret or a public private key and also clts can be encrypted also provide secrecy between parties you will focus on design tokens so they can verify the integrity of the claims contained within it while encryption tokens hide those claims from other parties so when we are using this the signature also certifies that only the party holding the private key is the one that signed it so when should we use json web tokens so like we do for authorization this is the most common scenario of using kwt once the user is logged in so we log in then every request that we make afterwards will be with the jwt so this will allow us or the user to access route services and so on with that token we could also make some information exchange where we can yeah transmit information between parties and we can actually sign like you can see it here adjacent web token always has three parts a header a payload and a signature and it looks something like this here we can have a look later on it so you can see it here this is an example from jwtio so these are the three parts the red the purple and the blue one and you see this header the payload and the signature and so this here is the header and this goes to decoded which algorithm is used on what is the type of the token then we have the purple thing this is like the payload so this can be used for example to store some data in it so we can later if we generate our own jwt token we can add here some user properties like id name email whatever we want to do then we have the verifying signature here you could type in here secret whatever you want yeah so you can see here we had a consists of two parts type of token and algorithm the payload are the claims and where we can add additional data so we can skip this here a bit and we have at last the signature we can take the encode header we encode payload a secret and sign that for example if you want to use the amec sha 256 algorithm we can do it like this here and then we have our secret and this is there to verify that the message wasn't changed along the way in the case of token sign with a private key can also verify that we send off the trade number t is who it says it is so you can see this would be like an example here and so now we want to implement this into an s3s and for this we can go over to the authentication part of the documentation of nistrias so we need this nearly in every application and passport is one of the most popular node.js authentication libraries and we can implement this by using the nsfs passport module so we can already install it so we can go here in our code and before we do this we have to go to our new branch so we say git flow feature start and then we can name it exactly like our story and then we are on a new branch um feature not a valid name here with rp dots and now we have a new branch feature and s2srwt3 based on develop and so now we can make all our changes so we can for example npm install add nest js slash passport and save it to our package clock json so we can with passport we can authenticate a user by verifying the credentials with username and password json web token whatever we want um we can manage the state by jwt for example attach information about the to be request object to do something with it later and let's go a little bit here so we need sjs passport we need passport itself i think um yeah and you can see here once we are authenticated the server will execute jwt that can be sent as vera token in authorization header on all following requests where we want to prove our authentication and here you can see for any passport searcher you choose you will always need venezuela as passport and passport packages then you will need to install the strategy specific package either password jwt or password local and i want to use the passport jwt package so we can say npm install passport jwt minus minus save and then we can implement the strategies for example we are having already our of module our outservice here we can go over this year um yeah we can just skip this here and skip this also so we could for example use um here are some guards later let's go to it here um so you can see here we can yeah pass for example a strategy directly to our off guard and we don't want to use a local off-guard but i think it's with jwt off-guard so we can verify so you can see here first we have to import the jwt module into our authentication module where we give him the secret and when the jwt should expire so you can see it here for example you can sign it for example with the time when the token was issued and when it should expire for example 10 000 seconds and then inside this module we can use the jwt services so for example here we have when the trade ability off guard which uses the out guard from um sks passport which we'll check if there's a valid trade wt or if there's a trade wt applied to this request and if not when it says no there's an error you cannot access this resource and the other thing that we want to do is we need the jwt strategy and this is for example here where we will extract from the request between wt from the offender has beer token we are ignoring or we are not ignoring the expiration and we validate this against our secret and then we can with the validate this is like the basic basic function this will add to the request if it was valid it will add the payload for example whatever you want to have like for example the user so we can then work in our back end with the user id from or that is specified in vitratewt token so you can see it here with jwt surgery um we have the trade wt from request here there we extract virtual wt from the request we have ignore expiration we choose false because if the variable t is expired the request will be denied and for one will be sent and we are using the secret.key to supply our secret for signing the token and this should never be exposed publicly at the moment yeah we will add this later to out of a compose file but in a production environment this should not be there yeah then we have this validate function here and this firstly says here that we are having like a valid token that is not um there's nothing done to it so you can see here as soon as i change something in the token if i add something if i remove something this token becomes invalid so this verifies that this token is correct and then the validate function will be adding to the request objective property that we can work within our backend so enough with this now let's start implementing all this here so we also need to npm install the nest js jwt package and so now we have some here we can check the first step where we make an overview over jwt and implementation in s3s we have installed i think all the needed packages if we miss some we will just import them or install them now we want to add a function where we generate we traded jwt to our authentication service so we go to our off service here and we add how we go into our constructor and here we simply add our gwt service and this is coming i think great wp service and you can see it here from our nspsjwt package and with this we want to generate jwt and we also want to return here an observable and we are just returning a string as an observable from type string because the vjwt is just a large string and as an input we take the user from type user interface and here we return from this jwt service so we make this an observable we signed async and we have to assign it with an object and this should be the user so this will be the payload and the other stuff that is need to sign we will provide here in our authentication module so we have to make our imports array and where we need our jwt module we can register this also async because we need here to work with um the secret so we have to give it in terms of we need to add an import here this is our config module and we need to inject our config service from s3s so that we can work with the environment variables and then we can use a simple factory um to use our config service and of course we should zoom in to use our config service and make a simple function and here we can say we want to have it with a secret and the secret we will get from our config service dot yet and then we get the trade wt secret and the second thing is we want to assign it with some options so we say it expires in and this is for example 10 000 seconds so we can just go over the next js config service a bit so with this we are able to grab from the environment variables the config or that value that we need so to get this we have to provide it and we can do this very simple our docker compose file where we have our api or an sjs part and here we can just simply add our kwt secret and we could for example name it normally if you add something that is very hard to guess like a combination whatever you want you can just do it like this here and normally you could not publish this in a video or anything after all so now we will get the strategy secret we will sign so these are the two parts that we also need to sign it here service will sign with the payload user with a secret of sign options and so on so this should work now then we have here imported our twt module and in our authentication service here i think this should be all so now we can go to the next part of our story so we have our jwt or generate awt function then we have imported the trade wt module to our authentication module and now we want to add our jwt guard and the strategy so then it will be clearer why we need those so in our module we can generate a new folder for strategies and we can make a new folder for guards and then we have here our jwt off dot got dot ts and in our strategy we want to have our jwt dot strategy dot ts and then we can start very simple with our guard and this yeah this is nearly copy and paste what we are doing from the documentation so this is our off guard [Music] so this will just verify this so where we extend the outgoing we can use this later to check that the request contains a jwt and then we have our strategy in this credit tree we can also copy and paste a little bit so of course we so then we have here our dwpg strategy where we are using passport strategy to extract the token from or or the jwt token from the request and then add here some payload or use the payload that we got to add this to the request so we can see this later so here we can say for example um this is the payload we can just add this to payload.user because we are signing this with the user object in our service we're assigning the user object then we can get the user from the payload and add this here to our request i can show you later what this will do and then we have here our gallery strategy this will extract ignore the ignore or will not ignore the extra x ignore the expiration and then we need our secret and yeah this is obviously but in our environment variable so we need here also the config service we import it and then we can just call config service dot get and then this is our jwt secret and so it will only call this validate if we see everything is correct so if there is a trade wt if we are ignoring the expiration is or if it's not expired and a bit signed with the correct secret here so i think we can go to the next part of the story so we have added our guards and then we want to generate a betrayal teen all of in function and here of course we now need to add them as providers also so we say our service is a provider then we have our [Music] jwt strategy as a provider and our credibility of god as a provider and then we can go into our user module and we can see that in our user controller we have our login route when we are going to our user service login at the moment if we we check if we use if or we search for user by email then we check if the password is valid if there's a user if it doesn't find the user this is undefined and then we will throw an http exception um but if we find a user with this email then we check if the password from the user is correct against the transportation database and so if it matches when we say look involve successful if not we throw an exception so this is something here we want to create the trade wt and sign it or add as payload our user object from the database so what we want to do here is we cannot we cannot use this user here because this is coming from the find user by email and here we are also providing the password property and we don't want to return this in the token even if it's a hash we don't want to return this to the front end or to the client so first we need a new function here where we just find one by id so we can simply call it find one we get an id which is from type number and we are returning an observable from type user interface and this simply returns from our user repository dot find one and we specify the id and then we can use it here we can very simply just say this dot find one user.id and then we pipe the outcome so the user that we get and we make a switch map to end the call and there we get and return a user and with this user we want now generate a jwt so we can call our outservice and generate our trader and as a payload we want to have our user now we have to see what is wrong here so you see now we have to cancel this here i think with the switch map from it so then we have because we don't want to return here also um the observable but we want to cancel this work with this and then return to point one and return then the jwt token that is created and now we can do something with this in the controller so this should now return us here bjwt token and to make it a little bit nicer looking we can pipe this token and we get this as an observable string so we are getting the trade wt as a string and then we can do something with it and we want to return an object to our client and this could be for example with the access token and here we provided the trade wt then we have our token type that we can say which is from jwt and we can say this is expires in and we say this is like 10 000 seconds so that we have some information in our client so then we can go over here and click so we generate now we trade up your team or log in function we have added defined1 to our service so that the password property is not being returned and then we want to implement the tradable t-guard on our endpoint so getting all the users and to simply do this we can use the used guards from nest cares and then we can very simply say we want to use our kwt off guard which will check if there is a valid trade wt attached to our request if it is then it will also go with the strategy and add the user so our payload to our request object and we can make this um so that we see it so we could for example i think it's the request object from um so if we're going with the express then we appear our request and we could for example log it out and then this should be our user so and we should see this in the terminal here here if we are not giving him a jwt then it should give us a 401 error here so now we can check we have done this also and then we can at last at another point where we check with postman so now we can build everything and say docker compose build we can already go here so we see we have here our three endpoints so the first one is to register or make a post request for making new user to get all users and this should now be restricted because we are not having a kwt provided then we should not get or we just should get an http error and if we try to log in then it should answer with a valid jwt and then we can take this jwt and this to this request here and then we should also get all the users in return so we have built it and then we can start it and now we can check against all the endpoints we see we have here our endpoints so we now can try to request all users this should not work because we're not having a jwt and so you see we are getting for one on unauthorized and we're not even going into it so then the second thing that we can do is we can log in and so if we log in for example with the wrong email we get user not found 404 this is correct if we have the right email button the wrong password we get also login was not successful but if you have the right email and the right password then we get our response our access token our token type and the expires in and we could now copy and paste this token from here and add this to here and then you can see the decoded token is here the user object and our payload would be id3 the name and my email and we have the issued ad so it was uh assigned it here now and it will expire in 10 000 seconds so in one and a half hours or something like this um yeah so this should work and now we could add this jwt as we are talking to our get request here so we can go into authorization and pause and very easily we add say we want to authenticate with the bearer token and copy and paste the bureau token to here and then make a simple get request to our users and you see we are getting returned to 200 ok starters and getting returned all the users that are in the database and you can already see here if we use guards first we go into we use our jwt off guards and we use withdrawal p strategy to check if the ex if it is not expired if the secret is correct so we get the sequence secret from our environment variables so from the docker compose and we extract withdrawability from the altera of header and if it is valid then we add to this request the user so from outside of our jwt we then get this user object here and add it to the request so that we can then for example work inside our service with it so we can now remove this because we don't need this comment here here i think this should be all for this video so we can now go to the story we say we checked everything with postman we can save this and we can commit all the changes and close the story so now we can stop the server or the docker containers and we can say get at upper a and make a commit message this starting thing should be again the name of our story and then we say implement kwt generation and at basic jwt guard to get users endpoint and then we can say we want to merge this back into our develop branch so we say git flow feature finish now we have it back on our develop branch we switched also to develop branch and deleted the old branch
Info
Channel: TommiCodes
Views: 7,832
Rating: undefined out of 5
Keywords: javascript, typescript, nest, nestjs, nest.js, typeorm, git, gitflow, node, development, api, observables, rxjs, nestjs7, bcrypt, jwt, authentication, git-flow, gitFlow, docker, docker-compose, pg-adminer
Id: 5ZuTuKUvhXk
Channel Id: undefined
Length: 38min 5sec (2285 seconds)
Published: Sat Jan 16 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.