Angular Login using Access & Refresh Tokens

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we will login using access and refresh tokens if we inspect the page and we refresh we will see that the user will fail the first time and then we will call the refresh endpoint and then the user will be successfully retrieved 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 angular with any of these backend frameworks and more because i don't know how many frameworks i will add i provided some links in the description of this video now let's build the app we will start with a pre-built angular app that contains three components the main app component at html will have the router outlet and the header on top which looks like this the three components will be the home component the login and the register so we will have only the html forms in these components because we haven't added anything on the component.ts pages and those will be added also in the routes there are also simple routes for each component and of course i added the bootstrap and some styles and in the end it will look like this this is a home component this is a login and this is the register let's start by registering a user before we register a user make sure also to run the backend pick a backend in the description of this video here i will start by going to the app module and here i will import two modules one is http client module to send http requests and the other one is reactive forms module so this will help us to submit the form let's go to the register component.ts and here we'll add the form variable as a form group don't forget to import form group from angular forms sometimes this may cause a problem here and i suggest adding exclamation point for the form here if you have problems that you need to initialize it and here i will create the form but to create the form we need to inject here another service which is the form builder is a form builder don't forget to import this also and the form will be equal to this form builder group and inside we need all the inputs that we have in our register here so we have three inputs the name the email and the password so here we'll set the name by default will be empty email the same and the password it is the same [Music] and that should be it now let's go to the register component.html first we need to set the form group to the form that we created and second for each input now we need to add the form control name and the form control name will be the value that we added here so this is name i'll copy this paste it here this is email and this is password so when we create a form group we need also to map the inputs via the form control name and now what is left is to to submit this form so let's add a function here submit and when we submit the form here we will submit it like this via ng submit or just submit and we'll call the submit function so we submitted the form and now we will use the http client so private http http client here to send a request to the backend with this information and we will send it like this so this http post to http localhost port 8000 slash api slash register is the end point and the information that we want to send are these values here and to get these values as we want we call this form get row value and that should be it in the end we will subscribe and we will get a response what do we want to do with the response we want to redirect to our login page so i will inject here private router router from angular router and when we successfully complete the form we will navigate to the login page and that should be it so this is the register form now let's register our user a email will be 8a.com and the password is a and we successfully redirected to the login page which means that we successfully registered now let's use that user to login so let's go for the login form first i'll copy the code from the register component and i'll paste it here directly because it will be almost the same we need the form group and the form which we add later here i will rename this to sign in we don't need the name we need just an email and the password and that's it for this login component.html now we need the typescript part so i'll copy also the code from here because it will be almost the same as well so we created the form where the the values here which we don't need the name we just need an email and a password and we will post to api slash login and that should be it in the end we will navigate to the main page but the login will be a little bit different because we will get from that an access in the refresh token to get the refresh token we need to add an option here which is with credentials to true because we will get that value from the cookies and to get the cookies we need to allow getting the credentials so we got the refresh token here and the access token we will get it from the response so response is any i'll cast it here and we have to store it somewhere so i will store it in an interceptor because we needed to use it later so let me create now in a new tab ng generate interceptor in the interceptors folder slash i'll call it auth so we created the house interceptor and the test file which we will remove it and this is the interceptor so what are interceptors now we when we log in we will get an access token and we want to use that access token on every request header and for that we need to add interceptors because they will stand between requests and here we can add the access token header in every request so let's do it first i'll create here a variable i'll i'll make it static and i'll call it the access token by default i will initialize it as md so why static i made it static because we will have only one access token and we don't need to initialize the class in order to set this variable so we can set that access token directly like this our interceptor access token is equal to response that token and that's it so the house interceptor we added to the access token as a variable and we will use it now in every request how do we use it in every request so we need to set this access token to the request header and to do that we have to clone the request i'll create another variable request so like this is equal to request dot clone so we need to clone it because the request variable is immutable and we cannot change the header there unless we create another variable with a different header so we can set the headers authorization and the value will be like this bearer and space and in this variable here we will add the access token and the way that we add the static variable is directly the other class so like this i misspelled the authorization we need an eye here and we will use this request variable now here but we completed the auth interceptor but we didn't add it to our app module so we can add the interceptor here like this we need to add it in the providers as an object where the first value is provided and that is http interceptors don't forget to import it here the second value is use class which is our class out interceptor don't forget to import this as well and the last one is multi i will set this to true and that should be it we added the interceptor and now how do we use it so let's go to the home component.html and here we will get the authenticated user so we will start by adding here private http http client and we will call this http get request to http local host port 8000 slash api user and if the response is successful like this we will change the message so i'll create a variable message here i will initialize it as empty and i'll display it here message like this and when we get the user we will change the value like this this message is equal to i'll cast this as any and this will be equal to high response name and let's see how this works now we are the signing page now and if i use the user that we just registered before we submit let's inspect and go to application here cookies let's see for the cookies so when we submit now we'll generate refresh token so we store that successfully with this with credentials to true we got the authenticated user because now when we send a request to the user the headers will have this bearer token which we send it via the interceptor so this is working as it should as well but if we refresh we will see that we are not getting the authenticated user because the token will be reset to empty and in this case we have to use the refresh cookie because we still got it here to generate a new access token so let's do that for the refresh token we have to handle that request when we uh have an error so i will add here a pipe so after we make the next request i'll add the pipe here and we will catch the errors so don't forget to import catcher from rxjs and here we will have an error i may cast this as a error as http error response and in the end if we don't do anything we need to return through error like this so let's import through error here and that and now we didn't do anything so we catch an error and we throw that there nothing will happen if i refresh the page now but now we can catch the error where the user is unauthorized by adding here an if condition if the error that status it is equal to 401 [Music] this means that the user is unauthorized and we have to send a request to the refresh token and to see if that works so for that we need to get here private http as an http client and we need to return here this http we need to send a post request to http localhost port 8000 api slash refresh we don't need to send any data but we need the with credentials to true because we need to send the refresh token cookie in the end we need to add the pipe here as well and inside we need a switch map so don't forget to import this also and this switch map will have our response here as any and what do we want to do here first we this will be similar to this logging component here so we need to set the access token in case it is successful so let's go back we will set again the access token so we set the access token and now we need to redo the previous request so this next handle request we did it previously it failed we sent the request to the refresh token and now we need to do it again so we have to return here now not this so this request that handle but we will not handle it from this variable here because this has a previous token we need the new token and for that i'll clone it again and i'll put it here directly so we need to use another request in the headers and that should be it so let's see it on the browser and we get the authenticated user now even if we refresh we will still get it because it will fail the first time we'll call the refresh endpoint we will get a new token and we will call the same request again so this is how we use the refresh interceptor still we need a small change here and we will see this change once we add the logout functionality which we will add it in the home component so here i will add an anchor link actually i will paste it so this will be just a normal button log out here and let's add the logout function for this so i'll add the function logout and when we click this button click we will call the logout function so in that function we have a http client ready so we will send an http request a post request to http localhost port 8000 slash api slash logout logout we need to send an empty body and we need with credentials to true because we need to send the refresh token so we can remove it in the end we will subscribe and we will redirect to the uh we will use router now private router router we will navigate so this router navigate to the login page the same we will do when we call this user in case so the user is not retrieved we want to redirect to login for that i will cut this code here i'll put an object here and that is the next case so i didn't change anything now just handled the success case and now i want to handle the error case which is another function but in their case now i want to redirect to the login page and that's it so when we log out now we will see another error i will go here let's click logout we will get redirected to the login page which is ok but if we go to the login we'll see that we are calling refresh a lot and i will stop it now so because this is an infinite loop why is this happening this happens because i will start it again here ng serve let's go to the auth interceptor we get there 401 and we call the refresh endpoint but when we log out we don't have the cookie so when we call the refresh endpoint we'll get uh 401 again and we will go here and we we will have an infinite loop here where we will have the same status and we will request the same endpoint to prevent that we need to call the refresh endpoint only once for that i'll create a variable here refresh is equal to false and if the status is 401 and we have not refreshed then we will call our refresh endpoint we'll set he this refresh is equal to true and uh if this fails we will go here but we will not do it again because the refresh is set to true we will go here where we have to set this refresh to false again and that should be it so we solved also the other problem now where we call the user multiple times and now we call it only once if we go there we can see we're calling user we are calling refresh and we redirect the next time so we have to log in again to get the authenticated user and the one last thing when we log out because we didn't put it here when we log out we'll set the out interceptor access token is empty now because the first time we it seems that we were logged in again so when we log out now and go back we cannot go back so that's it this is how we log in using access and refresh tokens in angular also if you want a more complicated course i provided a link for the ultimate authentication course with node.js and angular but you can pick a different programming language in the backend it doesn't matter here you can learn how to login using two-factor authentication and to social login using your google account and many more concepts if you are interested you can buy this course or you can pick a bundle so you can pick the nodejs bundle and you will get that course along with all my node.js courses just for 80 dollars a month if you are not in europe if you are in europe is 9.52 per month it is your choice and thank you for watching this video
Info
Channel: Scalable Scripts
Views: 18,688
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: OG8vbzVuFoc
Channel Id: undefined
Length: 22min 43sec (1363 seconds)
Published: Mon Feb 07 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.