Authentication With JWT Tutorial - React, NodeJS | How To

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys how's it going i'm back here with another video and today i'm really excited because this is a video that a lot of people have been requesting me basically in this video we're going to be making a authentication system using json web tokens and this is a topic that a lot of people are wanting to know and a lot of people have been requesting me because i believe it is one of the most important topics that you you can master using json web tokens is really important because it allows you to authenticate and verify if a user who is really who they say they are so if you don't know the difference between authorization and authentication is very simple authorization is basically what we did over here and this is a small project that i had before it's just a simple registration and login system when you register a username and a password the username and password sends the information to a to a database as you can see right here it's a mysql database and it also uh encrypts like it hashes the password while it's sending and yeah this is basically the system so that when we log in when we put the same information over here and log in it will look to see if the password and username we input it is exists in the database and if that if it exists it will say you're logged in this is called authorization basically uh it allows us it checks to see if there's a user in our database that exists with the same combination whilst authentication is something a bit different because when you're going to make an api request you really want to make sure that who's making that api request is the person who who are able to receive that information if i want to get a request that returns for example my password or sensitive information i want to make sure that the user making that request is the same user that should be receiving that information so we use something called json web tokens which is a way to authenticate the user and in order to do that i would come here to our project and you can see we're using react and node and by the way i know that half of the like the basic idea of a registration login system already in place here you can see right here i already did this this was done in the previous two videos because i had two videos explaining how to make a symbol registration and login system how to encrypt and not encrypt but how to hash passwords and how to use cookies and all that kind of stuff but it's really not necessary to watch that video to watch this one because this one is focused on authentication and authentication is something very different from authorization so i'll try to make it i'll try to separate what i'm doing in this video from uh what i did previously because you can see we have a simple program right here you can see i'm using sessions um i already have some endpoints and that's not necessary that you don't need to understand what this are because it's i'm going to explain everything and by the way before we go we go and start talking about json web tokens i would really appreciate if you guys could leave a like because i'm posting every single day while i'm in college so i'm putting a lot of effort and time into this channel and i'm really liking it so i would really appreciate if you guys could leave a like and subscribe so i can continue posting so the first thing we want to do is we want to install a package called json web tokens so you can see i have two terminals right here this is for the back end so i'm even going to close it this is from the front end and we're going to go here to the server so the back-end folder right here we're going to write yarn add jason web token i already installed it but it's basically like this if you're using npm just then it's just npm installed json web tokens web token and you should be fine after you install this you want to require the json web token library over here so we're going to go to the top and right below this by the way as i mentioned you can ignore most of this if you if you didn't watch my previous videos it is not necessary so down here you can see we can just come and say const uh jwt which stands for json web tokens and require json web token and now we have an instance of this package and we can take use of that so the basic idea is that whenever a user logs in we want to create a different a token that is related to the id of the user so for example this id right here and we're going to keep track of what that token is because while the users log in logged in we're going to be using that token to make every api request in every api request be it that the user wants to get for example his profile picture or the user wants to get then his name then every single api request we want to verify to see if the user who is making the request has the same web token as the user who should be making the request so the first thing we want to do is we want to go to the login route so as i mentioned before this was done before we have a post request which is called slash login which basically grabs the username and password that the user put over here and it makes a query like it it makes a select request from for our mysql database basically asking if the username is equal to that if it is then it wants to encrypt the password that we sent so that it will compare it to the password in the database and if the username and password compares meaning that the user is correctly logged in then it basically creates a session and for the user say basically saying that the user is logged in and it sends the results which basically currently is the username the password is everything related to the user so this is what we're doing right now but we want to add some logic inside of here which will allow us to create a json web token every time that the user logs in the basic logic will be as follow the first thing we want to do is we want to grab the id of the user you can see that at the top we are selecting all from users where username is equal to the username that we're going to that we input it over here but when i say all i mean everything we're also getting this id and this is what we want so we can come here and write const id equals to result and since our result returns an array since we're we can select multiple users we can only we can just say that we want the first user from that array and then we can just say id this is simple this is just what we did before like you can see the reason why we're putting 0 over here is because every every query request like every time you select something from database it assumes it may be it may return various like a lot of different rows and this time we're only returning one because there's only one username and password combination that is the same and but still we need to access the first element in that return and we're accessing the id why do we want the id well we're going to create our token based on that so we can come here and write const token and equals to jwt dot sign and this is how we're going to create it right over here we can pass the id so we're passing the id and then we can pass a secret and this is really important you don't want to just write as for example jwt secret i'm going to do this for this video because it doesn't really matter at all for me but if you're going to publish a like if you want to publish an application with this you definitely want to use env files uh you're going to create a nv variable and just put this right there if you don't know what our dot amv variable is it's something extremely important for any application but you probably shouldn't you probably already know because this is something that we start learning in the beginning because it is important that we don't publish stuff with variables that are that contain secret information so i just put jwt secret over here and then we can just pass an object and this object will contain some information about our tokens for example when we want our token to expire so when i say expires in we can just pass a value over here i'm gonna pass 300 which corresponds to five minutes i just always put it like this you can check the correspond like what this values correspond to in terms of real time and i would recommend five minutes that's a good amount of time in my opinion and that should be it right here at the bottom we want to finish with uh authenticate like setting the session just like we did before so this is something that if you're not currently using sessions then don't worry that much but this is something that we want to do and yeah that's basically it the only thing i want to do left like the only thing i need to do left is basically when we created our token we want to and we logged in we want to send that token to the front end so for example before we were just sending the result and remember that the result is all the information from the user that is trying to log in but now we want to change a bit we want to send for example we want to send a json instead of just normal send and we want to pass an object a json object that contains the following information the first thing is we want to pass if the user is authenticated so let's say that the user actually is authenticated because if it is like if we got to this point then it means it is authenticated then uh no no no no i actually don't mean authenticated i mean author authorized so the user created the uh the token then we're gonna pass the token and let's pass the token that we just created so token and finally i wanna pass just like we were doing before all of the results so basically all the information from the user including the id including the username including the even the password in this case but i wouldn't recommend passing the password to the front end but this is just what we're doing we're passing everything like we're gonna pass everything over here from the user who just tried to log in and in order to do that we're going to pass result right here and that should be fine okay so the next thing we want to do is we want to make it so that we just created a an instance so that when you log in to an account you create a token but now we're not doing anything related to authentication yet this is just creating the token when we want to work without authentication we want to authent authenticate whenever we're trying to make an api request for example let's imagine we want to we're here in the front end and whenever you log in a button appears saying get user info and that get user info will return a message saying hey you are authenticated the reason for that is because we just want to create a test um api request that is just going to check if the web token is correct and if it is it will say you are authenticated if it is not it will it will say you're not authenticated so let's do that let's come right here and create app.get we're going to create a request called user info for example now let's just say is user authenticated this is a horrible name but let's just leave it like this then we want to pass initially we don't want to like we want to pass a middleware right here and i'll explain exactly what i mean by that but then we want to pass like always the rack whereas and let's even pass it next actually let's not pass let's not pass the next let's just create a function right here and down here let's just say that if it is then we want to res dot send i don't know like yo you are authenticated congrats something like that so the idea of this is this is an this is an endpoint right this is basically asking we're going to make a request to this endpoint in the front end however the difference between this endpoint and every other endpoint in our project is that we're going to apply a middleware right here called verify jwt we haven't created it yet but we're going to create it right now this is a middleware that it's going to whenever we call this endpoint we're going to verify if the user making that the trying to reach this endpoint has the correct web token and whenever you're going to if you're going to use json web tokens you want to apply this middlewire to every other request because every request is sensitive like every request that that sends information that really needs to be sensitive so you're always going to apply the same middleware and we're going to create that middleware right now the first thing we want to do is let's just create it over here like it doesn't matter it just needs to be you just need to create it above where you make your request so i would actually create it at the top but currently i'll just write it over here so what we want to do is we want to write const verify jwt and then we want to pass rec like it's a function so rec and res and let's also say next and at the end let's just create the function so the idea of this function is that we're going to authorize what i like if the user is allowed so let's initially just write const first let's get the token so equals to rec dot headers and x axis token so we're grabbing the token right here and right afterwards we're going to say if token so if token wait let me write it correctly if token if not token uh we're basically asking if there isn't any token we're going to raz dot send uh res that send the uh a message saying yo we need a token please give it to us next time and you might already have seen like we're grabbing the token from the headers this is something important if you're working with json web tokens you'd want to pass it directly on the request you want to pass it through the headers so this is how we're going to actually send it and i'm going to show you guys on the front end how that works but if the if not if the not token then we want to send that but if there is a token if we actually have a token being sent to us then let's just say that we want to verify so jwt dot verify and inside of here we want to pass the token we want to pass the the secret that we created for example i remember i think it is jwt secret then maybe we want to pass a function so we want to pass a function that will first ask if there was any error verifying and then ask and then we will try to pass something called decoded which will allow us to decode our token and this is a function so let's come down right here and inside of here what we want to say is if there is any error so if there is any error then we want to say that it failed to authenticate so res that send let's actually pass an object so jason let's pass it similar to what we we had before so let's just say something like auth equals to false and let me see maybe a message so just like we had before you failed to authenticate and if there isn't any error meaning that we the the token is correctly verified it is the same person so it is corr like everything is okay then we want to rack dot user id equal to decoded id and i'm going to explain what this means the basic idea is that when we want to make a request further in our project we want to actually save to see if we want to save the decoded id into a variable called user id for example you could call it whatever you want but this is just so that we don't need to verify every time that we want to make a a request so this is just saving the token and it means that like the id and it means that we're going to be able to make authenticated requests further in our in our project but the next thing we want to do is we actually want to work with um with like verifying to see if this is the correct user in the front end so for example let's come here to our app.js and this is a react application as you can see right here and currently we just have a simple application like i mentioned before there's like an input asking for username registration a password registration a username to login a password to log in and then a button so that you can log in and at the bottom it says login status login status is basically the username i should have chosen in a different name but it's just the username of the user if the login status is equal to nothing which is how it starts then it means the user is not logged in but if i came here and for example i tried to log in i would say this is an account like this is a user i created its username is pedro 5280 and the pass rate is five two eight zero and click login then let's see what the console log says it says connection refused we actually don't have i know what it means basically we need to restart our server so node index.js it says running server we started again let me click again you're going to see that uh nothing like nothing was console logged but in our back end you can see in our network it says login is equal to true and you can see that what is sent through the back-end this is what we received when we tried to log in we received a adjacent with a variable called auth equal to true a result which is all of our information for example the username the id the password the username as you can see right here and we also received the token and this is what we're going to be using this is the important part of everything this is the token that we got so this is the basic idea right we received everything when we make a login as we mentioned before so this means it's working let's come here to our project right here and let's start working on off the the process of sending the correct header to our to any authentication request we want to make so let's create a after you log in for example so after you log in i'm going to come right here i'm going to change this i'm going to ask if login status login status is equal to um it's actually not equal to this and maybe should i should this matter actually no i'm going to change something login status should be a boolean this is boolean saying um saying true or false so it starts as false it's basically asking if you're logged in or not and it's going to start as false i remember over here this is when you log in after you make a login it asks if there was any error if there is any error let's set it equal to still false it means that we're still not logged in if we successfully logged in let's just set it equal to true so this is i hope you guys are understanding we created a variable called set login and it's going to be uh false in the beginning and if we log in it's equal to true if we don't log in is equal to false and over here i remember i asked for the login status oh no this is the error over here so we're going to ask if if we're if we are logged in so if we are logged in then we want to basically just render a button so we're going to render a button over here i'm going to close this so we don't receive any errors and over inside of here we want to initially just render button that's saying check if authenticated so this is going to be a button you can see that initially nothing happens but if i try to log in pedro 5280 and i write at 5280 the button should appear so it didn't let me see what happened um for some reason nothing appeared let me check um if the login status we did make the request we should have actually received the data why didn't we receive the data let me check network the request was not made let me try again it was made it was successful but why aren't we actually receiving anything this is this is weird i'm gonna check to see what happened and i'll come back okay guys i actually figured it out basically previously i was asking if the data. message which basically was a message saying you you didn't log in if it wasn't if it didn't happen meaning that um if it didn't work then we would set the login status equals to false but now what we want to ask is if a response so if response dot data dot auth is equal to false meaning if we're not authenticated this is what we passed over here if you remember so you can see right here we passed um authentication we passed token we passed everything so let's come right here and let's say that let's pass the same thing over here meaning that we're going to pass this equal to false we're going to not pass any tokens because there wasn't any tokens this is if there no user exists and we're also going to pass a message saying no user exists now let's do the same for this one right here this used to be wrong username and password combination so it's still going to be the same but we're going to change this to wrong username password combination by the way if you're confused with the whole authorization process i have other videos i'm going to link both of them in the description and if you want to check it out but this video is focused specifically on authentication this is why i'm not going over the other stuff but you can see now we have if the user if someone inputs a user that doesn't even exist we receive a json with an object called authentication equal to false and a message saying no user exists and if it also exists but the username and password are wrong then we want to send the same thing but the message is different and if it exists it's going to send that authentication is equal to true meaning that if we want to send our authentication variable to be equal to false we can just ask if if response.data.auth is not is not true then if it is then we could just say like we just want to set it equal to true let's save this and now let's try to log in pedro 5280 and 5280 and log in you can see now a button appears meaning that we are correctly logged in let's also see if the if anything was console logged two objects were console logged meaning that everything is working we are receiving all the information including the token so this is great now what we want to do is we want to create a function that will off we'll check to see if the user is authenticated if they click this button right so currently this button is just right here and nothing is happening to it but we want to pass something we want to pass a on click event i'm going to pass something called um authent user authenticated like this is just an example uh of a like of an api request that we might want to make that would check to see if the user has the correct uh token so for example we're going to create a function called user authenticated up here and let's create it i don't know down here const user authenticated equals to this then we're going to create a function and this function will make a simple x use a post request no get request actually and it's just going to make the request to the func to the endpoint that we created uh previously so let's just say let's just grab this but it's obviously not going to be login it's going to be wait let me try to copy again we're going to paste it over here and change this to get user info i think user info wait how do we call it we called it is user out what a terrible name so let's just paste it over here so we're making the get request to that endpoint then we're going to pass um nothing actually we're actually going to pass something we're going to pass headers and the headers we're going to pass is basically the token that we currently have so let's let's save this but let's also go to the end and say dot then because after the request we want to grab a response like always and after we get the response let's just come here to the bottom and i don't know let's let's just console.log the response the response would be basically saying if we are logged in then then it would say yo you are authenticated congrats this is the basic response right so the idea is we want to pass some headers what are these headers well remember that we're requesting a header down here in the i think it's in the verify let me try yeah in the verify jwt the token is basically passed on a header called x access token and this is what we want to create we want to pass we want to pass a header over here called x access token and right over here we want to pass a token but wait we don't like we're not keeping track of the token well this is what we're going to do now remember that if the user logs in we have access to the data we have access to the token including so let's initially just create a variable called const so actually let's not do this the idea is you don't want to keep the token into a state or something like that let's just put it in our local storage this is what most people do and i would recommend doing that but also there's like arguments against it like there's there's many different debates on whether on how you should store your your jwts let's say you want to store it into your local storage so which is probably the most common one so after you log in you want to come here and say local storage dot set item this is how you set an item and you're gonna say token and we're gonna set it equal to the response dot data let's see how it responds right remember when we log in we need to try this again let me let me actually do this and let's try to log in again so we can see how our response returns so 5280 and log in you can see that it says we received a response saying data dot token so we got to say data.token so set local storage you can just say response dot data dot token this is how we're getting our token but one thing is important and this is for some reason uh something that is important uh when you get this token over here and the back end for some reason that it requires that you put this tag this piece of text right here which is the word bearer and then a space and then you add basically the idea of this is that your token will be composed in the back end of the word bearer a space and then the token that we received over here so it should actually be you can see we received this token over here it should be bearer space and this and this is how we they're going to check in the back end so this is how we're going to actually store it in our local storage so now we're we just set our local storage item called token to be equal to the to a word bearer plus the token that we saved and then we're going to come here to our user authenticated and instead of setting this equal to whatever we're just going to say local storage dot get item and we're going to get the item token okay so if this if everything worked smoothly we should be it should be working so let's come here and let's also remove all of the console logs that we had previously because they're kind of unnecessary now we had this one we had this one i just want to receive the the console log saying uh yo you are authenticated so let's come right here say pedro five two eight zero then five two eight zero it shouldn't respond anything yeah it didn't it didn't console log anything but when i click on this it should give us a response saying you failed to authenticate let's let's take a look at why this is happening well the headers that we passed is let me see let's take a look at the request right so let's come here to network we made a request called is user auth the request was actually correct but it says you failed to authenticate let's take a look at what headers we sent um it's saying that we we sent um let me see over here we sent x axis token with a bearer and the token so that's correct now let's check to see if our local storage has been correctly set you can check for local storage over here and let's also check for this it actually didn't it didn't save anything right okay actually i didn't see it it's over here so the token is actually set on this in the local storage so why isn't it working well i'm gonna take a look to see why it isn't working and i'll come back to explain it to you guys okay guys i'm back and for some reason everything i said about adding a bearer it's actually unnecessary so i'm gonna delete this this is the token we're gonna come right here and the way to fix this i don't i don't understand why that didn't work it used to be a problem for me i might be confused on that thing but basically you need to you don't need to put bearer over here just pass the token and that should be fine it's usually i don't work i don't work on jwt's in this manner like i mean i usually work it on a on a little bit more different way but i'll just say that this this works right here if we're setting the local storage item to the token directly then we're get we're passing the header saying access token and now if we save this right here we come here and say i'm going to open my console log and if i say pedro 5280 and i pass the password 5280 and i click login you'll see that nothing appears but then when i click on check if it's authenticated it says yo you are authenticated congrats and that's great it means it's working it means now we are a user who is making api requests with the correct token and now that we we have that the the the id the idea that you're you're authenticated it's saved into your requests and when you make other api requests then that api request is automatically authenticated so that's basically the idea i don't know if this video was pretty long i have no idea but i don't want to make it so that jwts are complicated people have this misconception that it is something really complicated but it is actually not it's just keeping track to see if the user who is making an api request is actually the user saying that like the user they are claiming to be so this is something really important and i hope you guys actually got the the idea i am responding to every single comment so if you guys leave a comment down below with any questions i will answer it and yeah if you guys leave a like and comment down below and subscribe to see more i would really appreciate it and i hope you guys liked it so i see you guys next time [Music] you
Info
Channel: PedroTech
Views: 70,853
Rating: 4.8957653 out of 5
Keywords: crud, learn reactjs, nodejs, programming, react tutorial, reactjs, reactjs tutorial, typescript, react js crash course, react js, node js, express js, pedrotech, traversy media, traversymedia, clever programmer, tech with tim, freecodecamp, authentication, jsonwebtokens, jwt, authentication in react js, authentication with react, authentication with jwt, authentication with jwt node js, jwt authentication, jwt authentication node js, jwt authentication react, json web token
Id: KgXT63wPMPc
Channel Id: undefined
Length: 32min 18sec (1938 seconds)
Published: Fri Oct 23 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.