JWT Authentication Node.js Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome to a new class course as you know the title of this video it's about jwt authentications in node.js so when it comes to creating the sign up or the login feature on your website it's very important to understand how jwt works because it can protect the user information and also in this class course we learn how to hash user password before storing it in the database and we also learn how to generate token and how to validate whether the user is authenticated or not and we also look at how authorization work as well and there's a lot of things that we can learn in this class course and without further ado let's now get started all right guys so before getting into coding i first want to show you this diagram right here so basically i want to explain you the differences between authentication and authorization right so with this diagram right here first you imagine that this is the user sign in by filtering out the user email and the user password it can be through the front-end framework like react and then once that user providing all the credentials including email and password then we will create the system or the server to authenticate uh basically to the server would ask who actually who are you and are you actually authenticated right so we just want to authenticate whether that user actually exists in the database right so that's called authentications we just want to know who you are and next here once the user is authenticated then we want to see whether that user is authorized or have the certain permission to ud certain in this case you can see we have three posts uh post one two and three so the red one here is uh meaning that it required the uh log in access to ud content of the post three so that's something that we call authorizations right basically the server would say i know who you are but are you actually allowed to do that are you actually allowed to view the post number three here so the whole thing here it's called authorizations so that's the difference between authentication and authorization right now let's go to these code here so first thing that you will need to do is to create a new project so um this is the command it would be npm init dash y right and then press on the enter key because i already uh generate the package.js file so it will not do it here and also you will need to install six libraries that require in this project so this is the command npmi are you ready to install express library bitcrypt so basically we want to hash the user password we don't want to see the plain password of the user and store it in our database so we want to hash it to make it unreadable not understanding with the salt and i also will explain you uh what is salt and what each has right and this is the third ivory is the json web token or jwt i will also explain you this topic as well and this is the nodemon basically whenever that we make change to a workload then the server will automatically restart and this is the express validator uh what this does is to uh validate whether the user input is um correct or not so for say i will explain you again uh in this one in detail uh say like um the email format or the password will admit uh the requirement that we specify and this is the uh dot uh env so this is the environment file um that basically we don't want user to see some important information so this is the library which is right here dot env right so you will need to install this six library and now because i have already installed all of the six library what i'm going to do now is to start the server so in the package.json you can also see that this is the script that you will need to change so start nodemon we need to use this uh library whenever we may change to our code then it automatically restart the server so nodemon uh the file it will be index.js right here and then these are all of the dependencies that i just mentioned about right so now we already have um this package.json set up as well i want to start this application or start a server [Music] okay so now the server is starting it's listening on port 5000 so we can start with the index.js file here okay so first you will need to create this file called index.js and you will need to import the express here and to be able to use the express library you can define it in this available call app and then for this part right here express.json is basically we want to return the data in json format so that's why we need to use express.json and within the app.uh use okay so right here this is the path we have two path uh one is the slash off and this is lastpost right here we defined it in a separate file so slash route slash off so it's just right here right so we have the off and also the post and and the reason that we want to use that because we don't want to have all of the paths so for example right here inside the off.js we have like slash sign up and stuff right we don't want to use this format router.post.get there's a lot of file in this index file so do we just want to eliminate that that's why we just separate into the separate file using the app.juice okay and right here this is just uh listening on the port we specify this 5000 by default and now we can start looking into the slash off uh which is this file right here and now you can see that with this the first thing we do is to use the router right express the router and then down here at the end of the file we have the exporting that router okay so now next one here is the express validator we import the check and also validation result and we have the bcrip jwt and also the user which is our database and this is the dot env which is the important information uh so now we can start with this uh sign up right slash sign up so uh the first here is xsd uh midovia right so we use the check and this is the email that we want to check if there is um uh is it is not an invalid email so for example like say uh just typing right here it can be like say check add gmail but without providing the dot com right so it is an invalid email and that's how we going to check that right here and then this is the password you just want to check the length of the password so the minimum length that we defined here is six character long and this is the error message that we can also define we can just say in this case password must be at least six character long and this is the invalid email right so this is uh using the library called express validator and then down here we can start defining our function um we are using here is the async function and then down here this is the information that we get from the user so it can be coming from the front end right or in this case in this tutorial i use the postman for this example so in this case we get the information from the body here including the email and also the password okay so this is the information about that and once we have that information down here we validate the user input so this is the validation result right if there's an error then we store it in this variable and we want to return the error message right so it in the array format and we send the status code off of 400. so let me just quickly show you uh what i mean by that and here in the uh sign up right i'll be running on localhost 5000 off and the signup and the request is post request inside the body we select raw and the format would be json format okay so now this is the valid email and also wallet password as well but if i were to change this to something else like this right it is an invalid email when i click on the send button then you can now see we get these errors in the array format right and this is the value this is the message saying that it is an invalid email that we specified up here and down here this is just a param and the locations and now if i uh change this back here and uh the password instead of six character long i just put like five character and see if we get error message and now you can see the password must be six character long right so this is how we validate it and what if i put it something like this both are incorrect posted now you can see we get these two error message right in this object format so now let me just put it back to uh normal one so this is the valid one i will show you uh in a minute but now let's keep going uh with this one this uh we look into validating the user input including the email and password and down here this is validating if the user actually exists or not so this is basically we're just looking for the user right so the user email um it's coming from where it's coming from our database so this is the database.js currently we have two user in our database also for this example here i just store it in this js file and imagine that this is the actual database but you can also try to store all of the information in the real database right it can be like in mongodb or some other database that you like but in this example just for simplicity i just want to store this in this array object okay so um now we just want to check whether the email here and the email that the user input is actually the same if that is the same that means we don't want to allow the user to create a new account with the same email address and that's how we checked it right we use this dot find function here so now let me just also show you down here as well so this is the if that is true if that email is actually exist right then we can just uh print out this error message saying the user already accessed and we send the 200 status code and you might be wondering why do we need to send the 200 status code because it's just indicating the okay um if you try to look into like say a big company like gmail facebook amazon or twitter they are all returning 240 user that already exists okay but if you want to be specific it can be this error status code right 42. it just seems like the server understand the content type of the request entity but um other people would say that this is not appropriate it can be others as well so uh there's a lot of discussion regarding this but um for this example i just followed the big company using this status code of 200 right so now we already look at this one here as well i just want to demonstrate that to you so here let's just say i try to create a new user called shame user with the email james gmail.com when i click on the send button this user create is created right but when i click it again then you can see that the user already exists because it exists in the database right so now we also look into this part as well and before continue i just want to show you a diagram okay so this is the uh one that we already look into the second one here is the sign up flow right so there are six steps so first is two user providing the email and also the password that also show you in the postman here right and the second one here is to validate whether it is the valid email or the valid password or not and that's already we look into as well and the third one that we just look into is the validating whether the email is already exist right if it exists then we just want to show the error message that's the third step and the next one here is to hashing the password so now let me just scroll down and here this is the fourth step is to hash the password before we save it into the database and here you can see we are using this library called big crypt that we imported up there on top of the file right here right and with this here we use the function called chainsaw 10 so it's recommended to use 10 if you change it to like say 20 or 30 then it take longer it takes time to generate just a assault right and here i also try to console.log is sort to show you as well and down here this is the harsh password so we use the function uh bcrypt.hash and this is the user password that import from the front end right it can be from the um postman as well and this is the sword we get that sword put it here and finally we combine these two together with the uh using the hush and next is to showing the hash password in the console.log so now let me try to restart the server again and then try to create the same user so now let's just restart this and can be npm start or it can just make change to the file and press ctrl s it will automatically restart as well right because we are using the nodemon so here we just restart this meaning that the user that we just created called chain at gmail.com it uh delete it so now let's try to create the user again so simply press on the send button so this user is created right we can see all of the information here we will get into this um so now you can see that this is the sort right and this is the hash password so basically we just combine the sort here with the password right here and using the hash password this is the result that we get so we want to store the hash password in the database but not the plain um password right so in this case i just use uh for example i use this plan password right but actually we need to store information about the password in hash format here okay so now we have the information about the password right we store it in the database so basically we save the email and also the hash password to the database right so right here i just use the user.push and with the email and also the password here is the hash password okay so now we can't really see anything inside here because this is the javascript file but if i were to change or try to make the uh get request right to get all of the user so slash us last user we then will be able to see all of the information about the user in our database but i will get into that in a minute um down here we you can see we do not include the sensitive information in the jwt so this is the next step here is to create the or generate the jwt okay so jwt here we use um the await keyword with the jwt that we imported up there and this is the function called dot sign and we again do not include sensitive information such as the password in the jwt because uh we can actually uh decode the information back to original value right so we only import normally it is recommended to include information such as username or first name or last name user right or combination like the full name of the user but here i just use the email again it's actually not recommended to do that but just to show you that i just use the um email right here and then this one here this is the access token secret so um this is where it's coming from well it's coming from the env file right so you can't just specify any a secret value here any things that you like should be fine and then we just apply it here and finally this one here we just want to have the token the access token to expire in just 10 seconds so just for demonstration i just want to set this to uh 10 seconds but in real world application it can be 10 minutes or it can be 15 minutes right so you can just set the expiration time right here i just set it to 10 seconds and finally we just want to send the data which is the access token in the json format and that's why when you you can see that when i try to create a new user this is the information that we get this is the access token okay but this one here is already expired because we only have uh we set it here only 10 seconds right and now um down here i also include or explain you the differences between these two error status code one is uh 401 and the other one is 403 so um normally people get mixed up with this two status code the reason is that right here this is the 401 it's called authorized but actually it's not for uh authorization at all it's for it's used for authentication right not authorizations so basically the server would say you are not authenticated right and this one here this is a 403 it's 4b10 it's instead it this one is used for authorization right so the word server would say i know who you are but you just don't have the permission to access the uh this resource or the specific page on the website right so you just don't get confused with this status code so for one authorized it actually for authentication and for three it's for authorization right even though the name sometime can be confusing and next is to get all of the user right so it's very simple just router.get with slash users and we want to see all of the users so this user again is coming from our database which in this case we have two plus the one that we just created right this one here james gmail.com so to see all of the user here this is the endpoint using the get request last last user when i click on the send button right here then we can see the information right so this is the two that we already find in the database.js file here and the one down here this is the one that we just created shame at gmail.com with the hash password so this is the password that you will need to store in the database but not the plain one right so that is the uh one that we have looked into which is getting all of the users and next is i want to show you is to look into the jwt i just want to explain jwt how it works right so basically we have the client so this is the our browser and this is the server so this is the node.js that uh we are looking at now right so there are five basic step here so first step is to use a login via the client or the browser so the user sign in with the email and also with the password it can be through the front-end framework right like react right so this is the user sign-in via the client or the browser and the second step here is to the server will create jwt that containing the user information and send it back to the client so on the server here it just uh before generating the jwt i also try to explain you everything as well like whether that user is authenticated or not and also right around right so if that user is authenticated then the server create the jwt containing the user information so what type of information well we just look into that one as well so the information that we include in this example here is the email right so this is the email and you can also include information like the username as well right but not the password then we send that to the client and next is to the client will store the jwt or the access token in the local storage or cookies or these sessions on the browser right so this is um what the client has to do and next one here is the client here we'll send that access token or jwt back to the server and finally um the server will interpret the receive token to see that whether that user is authenticated or because um the token it can be expired i just show you that um our example here is token is 5 in just 10 seconds so that's how we need to check the user this over here interpret the uh receive token to see if the user is still authenticated or not or to see that the user is also trying to access certain uh resources right so these are the steps it just go back and forth right with all of the steps that i define down here and now let me just um show you the this part right here the server that create containing the user information um so it's in here the website right so this is the office of website jwt dot io and this is just an example right they have included here uh it's basically the encoded value here it's um separate in two uh three sections so the first part here this is the header and the second one here this is the payload and the finally it's just a verifying the signature okay so now let me just copy the access token that we have here i just want to show you just copy that and come here try to paste it here right and now when i scroll down you can see in the payload this is the information that i mean right containing the user information it can be email or the username but not the password and this is this part right here and how about this one it's verifying the signature okay so verifying right now it says that it's invalid signature why is that because we have to provide the access token secret right so this is what we have so far so just copy that come back here and we can just paste that secret here so paste it and you can now see the signature verify successfully okay so that's uh basically the uh how it works uh in terms of a jwt token it's split into three sections as sims okay so if i were to change something or add something right here right it say that it's invalid and it's wrong right so um that's how it works now let's just are coming back here okay guys so now that we look into this as well like getting uh the access token right and down here we also look into the status code and get all the information next is to look at the login the login route right here before getting into all of the code i just want to quickly show you this diagram so this is the sign in so basically we have three steps so the first step here is to get the information such as the user email and the password and next step is to compare the hash password let's store in the database with the user input right so we just want to compare with the um the password is actually much if that's much then we can send the jwt to the server that i also uh show you in this step here as well right so the client send each beauty to the server and server interpret right so this is basically the step that we will need to uh look into or try to create okay and now let's just uh coming back here now let's just look at the login so first we get the information from the user including the email and the password and then we look for the user email in the database so right here just use the dot find this is the javascript function we want to see whether the user email is actually exist in the database so first we just want to look for user email okay so where is this coming from again it's coming from here and with another one as well right so it this one so now we have three of this if i were to try to restart the application or try to restart the server then this information will lost because we are not storing in the actual or real database but for now we have that information right the um user email uh see if it exists in the database and next is to check if that user is not found then we want to send the error information all right it says invalid grandson okay so here we send the status code of 400 as well meaning that the user is not found i just want to quickly show you that right here so let's just say go into the login route here uh slash us last login and with the information in the body right and in this case say if i want to search or try to log in with the email that doesn't exist so we just randomly type click on the send button and here you can see this is the information that we get which says in valid korean so because it doesn't exist in the database all right and next is to compare the hash password with the user password to see if they are valid or not if they are much or not right so big crypt they have this function here it's called compare and this is the password that get from the user and this is the password that we store in database in this case this is indeed this is the hash password in database so now let me just try to log in using james gmail.com with the password here and click on the send button and see you can see that it's actually uh exists and it generates us the access token right and also one thing that i want to mention is this request so uh normally you would think that log in is to use get request right but the uh right approach or the right implementation is to use the uh dot post because we sending all of the information here to the database right so um next is to now let's just look into what's else we have if it's march or not if it's not much then we want to say email or the password is invalid so now let me just try to type uh password that is not actually the same as the one that we hash in the database so let me just send this and here you can see we get 401 um unauthorized so it meaning that the user is not authenticated and we get this mistake saying email or password is invalid so basically it's coming from here okay let me just um try to yeah get back to this one and next is to send the jwt so it's similar to the one that we just look into jwt dot sign with the user information in this case we include the email and then this is the uh token secret it's coming from this env file and then we just set this to expi in 10 seconds very quick right just for demonstration and we just returned the access token that's why you can see when i try to press this this is what we get the access token okay so that is the offer and the next one i want to show you is to uh use this access token right so uh now we can just coming back a bit at this index.js okay so next is to look at these uh post routes so it's coming from uh slash routes slash post so it's right here so let's just take a look here basically we also import the same thing the router and in this case we import the public post and also private post from the database as well so in the database.js you can see we not only have the users but we also have the public post um indicating that um so actually there is no space here um indicating that the public post it can be seen by all of the users right so user without log in access can also view this content but for the private post here this means that the pulse 3 is private meaning the user will need to sign in to be able to view this private post okay so now let coming back here you can also see we have in uh create or import the off token coming from uh middleware slash authenticate uh token so it's coming from this file right here okay so uh basically um the public post here we don't have the middleware specified here right but for the private post we define the off token so this act as the middleware and we just want to see if the user is authenticated then that user will be able to view the private post so now let's just take a look at the uh authenticate um the token.js file here so we have um import the jwt and also the env right dot config and down here this is the off um token uh that we have specified the request response and this is next and uh right here we have um two options to specify the headers so first one here uh is to use the uh authorization header and then um the token uh we it's normally in this form right it's bearer uh space with the token that we get right so this is the format the first format that you can use using the dot split function with the space here right and this is the one so we want to get the token that how we uh can get it so this is the first option and the second option is to use the uh directly using the x off token we don't need to specify all of this right and that's the second option that you can use so i want go detail like explaining you the differences uh why should we use one over the other right you can check that out as well but in this class course i want to show you using the x off token and down here we just want to check whether if the token not found then we want to send the error message basically it's not found we send the 401 status code and the error message will say the token not found or not provided and down here we want to authenticate the token so we have the try catch block here and this is the how we verify it so the jwt it does have the verify function just want to verify whether it's actually valid or not and this is the token that we get right and right here this is we specify i'll get it from the access token secret and then if it's valid we will get the user information remember that in the jwt we include the email right so it's right here right and then if we get the user information what to do next is to use the next here basically we just want to skip it to the next step right skip it to ud a private post right if it valid then we we can view this and if not we want to basically uh send this um status code of 403 uh saying that it's an invalid token so now let me just uh simply um show you right here so just copy this access token this actually uh not valid anymore because token only valid for 10 seconds and now let me just try to show you this one here so uh inside the header right a slash post last private the header here we specify x of token and this is the token so i just paste it here and click on the send button and you will see that it's an invalid token we need to generate a new one right and have to be quick under 10 seconds to be able to see the private post and for this one here this is the public post i just want to quickly show you that as well we don't need to provide anything so no need to provide the x of token you can just simply click this right so now you can see it returned 200 okay with all of the uh this is the public post all right that this one here without having to provide the user information at all like the log in detail okay so next is to demonstrate that to you guys so now let's just uh coming back here because i have already restarted the server so this user no longer exists we need to create a new one with the same email and also the password so click on the send button and now you can see we have this access token right so um right here i instead of using this access token to see the private post i want to log in first so it will be the username here with the password route here so i simply click on the send button and we get this new access token just copy that and go to the private post has to be quick and uh paste click on the send button and now you can see we can view the uh post three it is uh saying that view three is private and now when i click it again it's already expired so click it and now you can see it's a invalid token because i set it again to just 10 seconds you can set it to 10 minutes or 15 minutes that also works fine okay so yep that's uh basically how we look into the jwt authentication right so um we uh in this class course we only look at the access token okay so we only look at the access token here that i specify here right getting the access token in the post and also access token in the login right but not really looking into refresh token i will also try to explain you the differences between access token and refresh token in upcoming videos but for this tutorial or for this class course this should be enough to get started or try to understand how everything works in jwt right regarding the jwt topic and before i finish this video i just want to quickly show you um the validator as well to check or validate the email or the password right you can either use the express validator so in this tutorial we are using this one here or you can also use the other library it's called express joy validation right this is also popular so yep that's pretty much it guys uh we have learned uh about jwt i hope that you learn a lot from this topic regarding storing the user information especially a hashing user password and stored in the database and how we generate the jwt and how does it actually works which i also try to explain you this here as well and if you have any questions just let me know in the comment section down below it's very interesting to create um this class course if you notice you can see that most of the website does have the sign up and also log in for the user right and it's very important to understand this topic so that you can implement it correctly as well as for the security purpose and until then see you guys in the next video [Music]
Info
Channel: Hong Ly
Views: 456
Rating: undefined out of 5
Keywords: jwt, json web token, jwt authentication, jwt authentication node js, node jwt, node, jwt node js, node jwt auth, jwt auth, node auth, jwt tutorial, nodejs, node js auth, jwt nodejs, jwt token in nodejs, node authentication, jwt node js express, jwt auth node js, node jwt tutorial, jwt authentication node js tutorial, jwt node, jwt vs session, jwt auth node js express, node auth tutorial, node js, node api, jwt token, what is a jwt, jwt login node, jwt en nodejs, bcrypt
Id: S4_vB1T4jWY
Channel Id: undefined
Length: 43min 11sec (2591 seconds)
Published: Sat Oct 02 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.