React Login using Access & Refresh Tokens

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we will register a user we will log in with that user and we will get the authenticated user the way that we will get the authenticated user is via access and refresh tokens and in the end we will log out before we build up i would like to remind you that this video can be combined with other videos so if you want to use react with any of these backend frameworks and more because i'm not sure how many backend frameworks i will provide but your best bet is to check the links in the description of this video and there you will probably find the backend framework that you like also if you want to build a more complex authentication system i provided a link for the ultimate authentication course with node.js in the react but here you can select also your favorite backend framework it doesn't really matter what matters is that here in this course you will learn two-factor authentication with google authenticator and also you will authenticate using social authentication with your google account and many more concepts you can get this course via scalable scripts.com or you can get all my node.js courses in this case for just eight dollars a month if you're not from europe so now let's build the app now let's create the app we will start by running mpx create react app i'll call up react alf and let's wait till this is completed now it is finished and i will open the project with my ide here i will open the terminal and run npm start and this will start our app on port 3000 and this will be our react app now let's make some changes go to the source folder delete the test file we will not use it in this tutorial go to app.js and here we will change the html we will use bootstrap in this tutorial so go to getbootstrap.com click get started copy the css link here and let's add it to our public index.html i'll paste it here and i will save it then in our update.js we need to add another html go to examples now and the example that i want to copy is the sign-in form so we have this sign-in form and here i will view the page source and i and i will copy this html from the main tag and i'll replace all this html with the main tag there one thing that you need to change is you need to change class to a class name my ide does this automatically but if yours doesn't make sure to change the class here to a class name and also let's remove the image here let's remove also this checkbox and this paragraph in the end and also these inputs we need to close them otherwise they throw an error and that's it so if we go to our react app now we'll see this form still we need some css which is located here a link ref sign in css i'll click this link and i'll copy this code so not all css code but just the form sign-in code i'll copy it and i'll paste it to up css i'll replace every css here with the css and our form now will look better now let's create some components so components here we need in this app three components we will create a login component a register component so let me create them and a home component so let's go to the login we will export the function login that in the end will return this html from app.js so i'll move this form to the login here and here instead we can use login like this this will work the same we will see now that our app has not changed still we needed to use react router down now to switch components so let's do it let's open a new tab and install npm install react router dom and from react router dom we need to import some components from react router dom the first one is browser router which we need to wrap all our components here with the browser router and inside we will have our routes so let's add the route for the login so we need to import routes and route from react router dom we need to add also routes here and inside the routes we need to add our route that we want so this route the path will be slash login and then the component that we need to render is this login component but we need to use element because this is a react router version 6 and we will use element here and the element will be this login that we had before and that's it so with this we won't see anything unless we go to slash login and here we see our login page let's do the same now for the register component first let's create the component export constant register this will be a function also and i'll copy the form i will paste it here and i'll make changes here so first here i will rename it to register and i will add another input which the type is text this is name and the label will be just name in the end we will submit and that's it for the register component let's add it to the routes as well i'll duplicate this and the path now is a register and the component is a register here so don't forget also to import it here and now if i go to slash register on the browser we will see the form and we added another input the name so that's it we added these two routes but we also need to navigate between two routes instead of just typing the url so for that go back to get bootstrap.com examples and go to the headers now and we will copy this black header here so i will inspect this time because it is hard to find it uh if you view the page source so i will copy the html directly here and i'll paste it here don't forget also to change the class to a class name and here we will remove this svg and for the urls here i will keep the features only the features here not the home i will remove the home because it stacks secondary i'll keep the features but i'll rename it to home because i wanted the classes there because home has a bit of a gray highlight here and i wanted a white one so i kept the home i will remove this form and this is login and sign up i will rename this to register and when we save it if we go to our react app it will look better i will also change the classes here to be the same with login and register and that should be it so i will close bootstrap now let's add also the home component so let's export here a class a constant home and for the moment we will return a div saying hello and we will change this later let's add it also to the routes here so this is a main route and the element here will be home and to navigate because currently we are not navigating between components we need to change this anchor link to just a link and that link we need to import it from react router dom and this is link and it will point to the home route to the home path same will happen for the login and the register so i'll change this button to a link to log in here and here will be a link to register and that's it now that i saved when i click login i will go to the login page when i click register i will go to the register page and i when i click home i'll go to the home page we can see hello here but let's change the message in the middle so i will add here the class name it will be form sign in it will be margin top five and text center and that should be it i'll make this also an h3 and it looks better so i'll keep it like this now let's go to the register and make the registration work also make sure that you have the back end running if you have the back end running then let's submit this form now now for each input so we have three inputs name email and password we have to use the react state so we have to create a variable name also function set name which will be equal to use state and the default value will be empty so for each input we have to do the same i'll duplicate it two more times and this will be email set email and this will be password set password and when we make a change to the input here we will add unknown change i will add it like this on change we'll have an event and we will set the name to event.target.value when so when we change the input we will set the name let's do the same for the other inputs so we will set the email here and here we will set the password so we set the values and now what we need is to send this data to the back end and for that we need to submit the form i'll create a function here submit and when we submit this form on submit we will call this submit function here this submit function will have an event and to prevent the form from uh refreshing so we can see when we submit here the form refreshes to prevent that we have to use event dot prevent default if we do that i refresh myself now if we type submit now we can see that the form is not refreshed and now we need to send a request to the backend for that i will install another package npm install axios and let's import access from access and we will send an http request now i'll make this function asynchronous and here we will await access we'll send a post request to http localhost port 8000 slash api slash register so this is the endpoint that we need to register and the data that we will send are the name the email and the password like this usually we say we set name is equal to this name but since the key and the value are the same name we can just put it like this and javascript will understand this and that's it in the end after we successfully submit we want to redirect to the login page and for that we need another variable here navigate set navigate is equal to use state and this time the default value will be false and in case navigate is true we want to navigate to the login which we need to import now navigate from react router dom and here we will return navigate we need a tool here slash login and where we will set this navigator through if the form is successfully submitted we'll set navigate to true here and we will successfully redirect to the login page so with this let's try to register a user i will create this user aaa.com password is a we will submit and if we redirect to the login page it means that we successfully registered our user now let's do the same for the login here we need to submit the form and we need to send less data we need to send just the email and the password still i will copy from the register all this code here and i will paste it to the login don't forget to import your state here and also axios is already imported in my case here we don't need the name so i will remove the name i'll remove it here we need only the email and the password and we will post to api slash login when the navigation is true we will navigate to the home page and let's add also the changes here when we change the input so on change we'll get an event and we'll set the email to event that target that value same will be for the password set password so we will set the email we'll set the password when we submit the form so we need to add here on submit we will call this submit function and this submit function will post to the login and now this login will be very tricky because here we will get an access and the refresh token the access token we will get it directly from this request so we'll get a response and this response will contain the access token but we need also a refresh token and the refresh token we won't be getting it in the response the refresh token we need to add here an option with credentials to true so we need this option because the refresh token we will get it via a cookie and in order to get cookies from requests we have to add this with credentials to true and that should be it so we got the response let's console.log for the moment response that data and we will not navigate let's see what is the response on the server so here i will inspect i will go to application cookies and for the moment we don't have any cookie also the console i will clear the console we will check these two tabs now now for the user that i just created i'll put the email address and the password when i type sign in i'll get here refresh token as you can see so we can get this refresh token if we add with credentials to true so we added that refresh token and if we check here the console we can see that this other is the access token for the moment we are just console logging it we are not using it and to use it i will use it like this first we need only the data here so i'll deconstruct this response i'll get the data directly like this as a variable and here i will add this code axios defaults headers common authorization is equal to a string with bearer space and the second value is this data variable with the token so like that what did i do here now every request after we login we will have the authorization header with the bearer token so this is what is needed to get the authenticated user which we will get it in the home component so here i will add another react hook use effect and we need to call the backend to get the authenticated user here the first parameter of user effect is a function and the second parameter should be an empty array if you want to call this function only once you need to add an empty array here otherwise this will be called a lot and now in this empty function we need to send asynchronous requests but this does not accept a sink in front of it so for that i will make a function that will call itself and inside i'll make an asynchronous function so this is the way that we can call asynchronous functions and here we will get response which is equal to weight axis get and we want to get the authenticated user from http localhost port 8000 slash api slash user and the response will get to the authenticated user and we will display the name here so create a variable name set name which is equal to use state the default value is empty and when we get the response we will get to the data here so i'll deconstruct the response and we'll set the name to data dot name and that's it here i'll change hello to hi name so that should be it now if we go to the home we are getting high but we are not getting the name because as you can see the response from the server is unauthenticated why is that the reason is because the token probably expired so if we want to see the name we have to login again and we can see hi a is the name of the user and as you can see now we are getting the authenticated user and if we see the request we will see that we will have an authorization here a better token in the request so when we log in here and we had we set here the authorization for all the requests all the requests will have this token but if we refresh the page that won't happen anymore if we see the authorization header does not exist right now so we have to do something for that also even if we login the token will expire in 30 seconds so in this case we need to use the refresh token which is stored in the application cookies here we have this refresh token and every time the access token is removed or expired we need to use this refresh token to generate a new access token and for that we need to use axios middlewares so i'll create a new directory right now i'll call it interceptors and inside i'll create a new file axios and this file we need to import it directly here import interceptors access like this so in this file let's go to access.js here we will first import access from access and let's add some default values the first one is access that defaults that base url is equal to a value so this value if we go to register and login it will be this prefix so i'll cut this code and i'll go to access.js and i'll paste it here so all the requests now will have this prefix and our requests will become much simpler for example this one looks better let's do the same for the login we will remove this part here as well this one looks simpler as well and in the home we will remove this part and our app will work the same even if we made this change so if we try to log in now we'll see that is working fine and now let's add the interceptor so to add the interceptor add here axis interceptors response use so this will have two functions the f the first function will get a response and this is the success case for this i will return directly the response so we don't want to handle the case where the response is successful we want to handle the case where we have an error especially an unauthenticated error so that error is i'll add an if condition here if error response that status is it equal to 401 so the server will return this status when we are not uh authenticated and if that happens we will send another request to the back end to refresh the token so we'll send we'll get a response here is equal to 08 so let's make this asynchronous wait here access again will post to the refresh endpoint and we will send no parameters this is required but we also need to send the cookie every time we want to send or get the cookie we have to use with credentials to true so in the case that we get the authenticated user here we don't send here the refresh token we just send here the bearer token so we send only what is needed we don't need to send the refresh token here and the refresh token will be sent only on three requests the login where we get the refresh token this request when we refresh the token we get a new bearer token and the last one we will add it later is the logout where we remove the refresh token so we'll send this request and the response will get us a new access token so first we have to check if there is response is successful for that i'll make a condition if response that status is it equal to 200 so this is the status that the response is successful for that then we need to add a new bare token i'll copy this code and i'll paste it here so we will use access defaults headers the authorization header will add the new bearer token and the token here is a response that data and this token so we added the bearer token and now we need to redo the previous request for that i will return here access and inside i will add error.config so error.config this contains all the information regarding the previous request that failed and if we wrap it with access it means that we have to redo that request again so when we get the user here it will fail because the access token will expire then we will refresh the token and then we will do that same request again with the new bear token that is the logic here in the end if the response status is something different we have to just return the error like it is and that should be it so we added this code now and what does this code do first we can see that we are getting the authenticated user right now so it seems that is working if we refresh here we will see that it is working we requested for the first time the user which it failed and then we reque we requested the refresh token the refresh endpoint sorry which we generated the new token and we requested again the user which we got the authenticated user and that's it basically this is how we use refresh tokens and now what is left is to log out so let's go to the home and here i will add a button here so this will be an anchor link href will be javascript void 0 because we don't want to go anywhere this will be log out here let's add some class names so class name will be button button large and button primary and it will look like this now when we click here we want to get logged out so first we need a function submit and or i will call this logout and when we click here on click we'll call the logout function and here we will call again axios so i'll make this asynchronous and we will await access post to the logout function the second parameter is empty because we don't want to send any data but we want to send the refresh token so we need to add with credentials to true so this is the last endpoint that needs with credentials all the other endpoints does not need with credentials and that's it and after we finish we want to get redirected to login navigate set navigate is equal to use state false and we have to set here set navigate not name to true and i'll go to the register i'll copy this code because it will be the same so if the navigate is true we want to navigate to login and that's it so we finished almost everything when i click logout now we will certainly remove the refresh token but we still have a problem that is happening right now as we can see we saw before that we had a lot of requests happening and when we clicked logout that problem will happen so let's click logout we redirected to the sign-in page and we removed the cookie but if we go to the home now we can see that the refresh token is we are sending a lot of requests so now i will stop the server here and i will restart so why is that happening i will refresh again here that happens because we haven't done the condition that if we are unauthorized and we still send a request to refresh the token we get again unauthorized and we send it again so this will be an infinite loop so we have to call this refresh endpoint only once and to do that we need to use another variable i'll create here a variable let refresh equals to false and i'll add the condition here if the status is 401 and it is not refreshed then we will refresh so when we go here i'll make refresh to true and if this fails we will go to this condition but refresh this time will be true so we will go down here and here i will set refresh again to false and that's it this is what we needed so this will make sure that we will send only one request to the refresh and we will not have an infinite loop so with this i'll go to the home now and for sure we are requesting it only once we are sending a request to the user we get unauthenticated and now we will send the request again to the refresh token which will get again unauthenticated but the request is only once and uh when we are unauthenticated i don't want to stay on this page so let's go to the home i'll wrap this with a try catch and if an error happens we are unauthenticated i will set navigate to true so i want to redirect to the login page so if i go to the home now i cannot go i'm getting redirected to login and we need to log in in order to go to this page and that's it this is how we login using access and refresh tokens thank you for watching this video don't forget to like share and subscribe thank you
Info
Channel: Scalable Scripts
Views: 50,060
Rating: undefined out of 5
Keywords: coding, programming, full stack development, scalable scripts, programming tutorials, developer, coder, software, laravel, react, vue, angular, django, python, nestjs, nextjs, nuxtjs, golang, denojs, nodejs, microservices, docker, kubernetes, rabbitmq, kafka, event driven architecture, event driven design, containers, mircorservices architecture, api, spa, single page application, c#, java, kotlin, .net core, java spring boot
Id: VJLSaq1Ll0U
Channel Id: undefined
Length: 38min 32sec (2312 seconds)
Published: Mon Jan 31 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.