Part-3 Angular JWT(JSON Web Token) Authentication(Refresh Token Implementation)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to episode number three on jwt authentication in angular application uh in previous two episodes we have mainly discussed on jwt authentication regarding the implementation of usage of access token so in this episode the main targets are like consuming a secured api using the access token as a authorization header that is one main target and next is invoking the refresh token on expiration of the access token using the http interceptors in the angular so these are the two main concepts today we are going to implement and understand regarding about them okay so our first step is i i want to consume a secure endpoint by using the access token as authorizator so before going any further this entire video has been made as blog okay this entire video you can check like angularjwt authentication mainly focus on the refresh token in this blog so here entire video session is made as a blog if you want to check the blog link it will be available in the description section under the videos so you can check there and this is the entire video so i in in part two i have shown we are using nesterjs application for authentication right in the same application i have created one fake secured endpoint like to do send point where it need authorization header to consume it so here we are going to use consume use that produce api into our angular application so further you can check the documentation little bit of documentation regarding that end point here itself next js studios api okay an sj setup and everything i have mentioned in the part 2 video if you want please check the part 2 video first and the end point is just simple to do send point the ultimate output from this end point is just a array of strings nothing else the main target to do this step is to understand how the authorization header will be added to our request in angular application okay now we have to consume this uh endpoint so before going any further please make sure that your nest js application is running in your local system so if you observe here this is my next j server application where it is up and running and here you can observe as well all the end points it has here it is also has to do send point so now here if now we are going to consume this api okay let's go to our angular application so for this demo purpose i am going to consume the to do say endpoint also in our service only but in real time example sorry in real time application please make sure we have individual service files for their respective endpoints similar endpoint okay going to create a new method that going to call the this angular data for today's data so to this dot http dot get it is simple get query only you can observe here okay get endpoint it is and i am going to copy the whole url from my blog okay tag will be observable let's make it any okay that is the logic for calling the api now what i will do i am going to consume this secured endpoint in my dashboard page when my logic is like i will add a one button or like show to do when user click on show to do this api will be invoked okay so let me go to dashboard component [Music] here like i'm going to call show produce okay this is going to fetch me some data like sorry in this i am going to implement logic layer i will call auth service where i have to do's and i am going to subscribe here of any it is most likely to be collection of produce like array of strings so here i am going to create a variable like produce whose initial value is empty array okay and i am going to assign value data to produce okay now in my html i am going to create a dashboard component html i am going to create a button okay like show to do's okay i will register click event okay i'm receiving data i will bind the data into another url of list early okay now first step let's try to consume the secured endpoint without any authorization adder and see the output how it will behave it is our angular application is up and running let's test here i got my go to this button okay go to network call accessor let me click see i am successfully invoking my secure endpoint but the response from the server is otherwise because it is a secured endpoint where it requests the access token as its authorization header so in angular to add the other any headers the main the technique we have to implement is http interceptors interceptors are nothing but uh like functions that are going to add some additional data before the request is triggered to server okay means nothing but it has capability to modify the request okay so let's create a what i can say uh interceptors for that go to my project and instead of the shared folder i am going to create one more folder like enter vectors okay inside of it i'm going to create a file like auth dot enters chapter dot ts okay let's create a interceptor class okay to make this earth interceptor is a angular interceptor it need to implement http interceptor okay if you go up it loads from the http module and here it will have its own predefined pre-built function that will always get executed if any http request is taken from the our application so one thing i want to mention is http interceptor will exit for all api calls it will it will intercept for all api calls if you want to escape from the functionality instead of any particular interceptor we need to write manually condition like based on the url we need to skip the interceptor okay and let me implement so it has method like interceptor it has input parameters like a request request is nothing but it will this object contains the triggered api request and next is nothing but uh like we are we are allowing to accept the flow okay if you if we have multiple interceptors this next will transfer the request to next uh interceptor like that if no other interceptor it will directly trigger the request to directly send the request to the server itself okay that is the use it is like a middleweight if you if you have any server side knowledge it's like a middleware only okay and now we have here we have to add our uh what i can say our authorization header like access token as the authorization header for that what i am going to do i am going to import the my au server as service and lets inject our service into our interceptor constructor class okay now what we are going to do we are going to use the user info object from the earth service where we can get the data like uh i can say uh it has the data like user information like user id username access token refresh token everything inside of the object so let's fetch the user data so here we are going to check logic like if we have user data and something like i will check for user id if they exist means i have available logged in user data then i am going to implement my logic else i am going to continue allow the request to process okay and let's return it it is like nasty dot handle sorry okay now if we have user information what we have to do we need to add our uh request every endpoint request the authorization header with value as access token so for here adding addresses nothing but to the modifying request right so when we are modifying request please never don't do on the original request so what we have another option like cloning the request object to prepare it as a new request object so we are going to use request.clone like equal start clone okay address okay request start that head start set the right json header and here here we need to pass the value nothing but our uh jwt authentication token for jwt authentication token we need to prefix our token with the error it is a barrier token and here i am going to pass my user data dot access token okay and assign this newly created request to a variable like launched new request okay now i am going to allow my process to execute request to execute for that i am i will return extra dot handle new request okay so i think we are good for adding the authorization headers let's test in our application before testing here what i want to do i want to clear the existing application so just do it like this clear we have login right and i know we are we have credentials like test and one two three four let's try to log in okay we are successfully login right now let's try to click on the show todays still we are getting unauthorized sorry okay we haven't integrated our http interceptor into our application workflows for that we need to register this http interceptor in our app module now we need to configure our interceptor in our providers array this is also like a service only but for interceptor configuration is a bit different okay here we have to use for this provide we need to give a interceptor token like http interceptor that slows from the http interceptor and next we have another property like use class here we need to give our interceptor class name let's import it from like shared interceptors earth interceptor and earth interceptor earth interceptor and another option like multi set it to true so that is the flow of integrating our interceptor into our application and here we have one more i missed one more thing like earth interceptor is a service right it should be injectable so let me write injectable okay that loads from the angular core and save it okay remove this semicolon from here and i think now we can test our application just now click on the show to do's till we are getting unauthorized okay our adder is added but i am getting another because the token i am sending here is expired that is the reason it's showing like uh an authorized response see here authorization barrier and token talking is i am sending to the secure endpoint but it is uh expert so it is returning another so in later steps when we implement refresh token this problem will be resolved so for now what we will do let's go to application and clear the browser local storage and re-login into our application okay test 2 3 4 successfully logged in and go to networks clear the existing network calls and click on show now see we got 200 and i have got response okay but my data is not binded let's see the issue so the error for the reason behind for ng for uh in the html issue is that is due to we need to import the common module wherever we are using this ng directory okay so in my dashboard i need to import the common model this is the most common issue that will occur when we use lazy module structure so please be initialized on top of anything okay you if some cases if still you see the issue once stop your application and start and update again okay now i will check my application i think console error that ngf is gone so let's go to application and clear the cookies because i have created the token with short time access token expiration so it always expressed after one minute i think so please clear the cache and reload the page and re-login to our application once again one two three four okay now i got logged in and i go to networks clear the existing cache and now click say now i am getting produce 200 this is my to-do list that was binded to the page and if you go to the headers here you can observe authorization is added with the help of interceptor so that is how we are going to add a authorization request with the value of our access token to consuming the secured endpoint in our application okay that's it about the consuming the secured endpoint interest and next thing is we need to check for the refresh token so i will wait for one minute i think let me check how much time i have it for expiration 30 seconds so i think it should be expired by now let me test it see my token is expired this is happening because i have a token that is expand so to resolve to resolve it we have to use concept called refresh token refresh token where we are going to it is a key like a access token but it is short key which is long lived more than the access token so instead of asking the users to enter his credential every time on the expiration of access token uh in general what everybody will do they will use a refresh token refresh token will be sent to the uh that jwt server so jw server validates the our refresh token if it is a valid refresh token then it will create a new access token as well as the refresh token and it will send back to the users so without re-entering or without user to asking for a again enter to credentials we can use the refresh token concept so in my case up to now we haven't checked the expiration of the access token in our application right now we need to check the access token expiration before we are going to add the taxes token as the authorization header in the interceptor so now the flow is we have to check first before if we go here and go to our path interceptor here we are directly assigning our authorization header right now what we have to do we have to check for the access token expiration if it is not expect we can leave this flow as it is it is if it is expense then we need to call the refresh token endpoint refresh token endpoint will give the response with new access token and new refresh token that what we have to do we have to same logic what we did for login page so i let me go to earth service what we did when we got the access token and refresh token we show them to local storage and decrypt the access token and assign it to the user infrared same logic has to be implemented in our service as well when we get the response from the refresh token endpoint so what we will do we will check the first step is we will we need to check the expiration of the uh user access token for that what we can do if it know less than what i can say i'm going to use number function and here you will pass i have used the data expiration in expat column right if you have doubt you can see a token expression sorry is to work in expiration right copy that and copy paste that into our interceptor and make it to seconds and then if it is if our current time is less than our expiration time that means our access token is still alive we can use that at that time what we can do simply copy this and paste it here okay next next what is a here if it is not expired it will uh proceed the execution of the request flow here only because we are here we are returning our handler right if it if at all it is expect next we need to implement our logic so if at all it expires we need to invoke the refresh token for that i in my blog i have given some documentation for that in my blog i have given some documentation like if you go below here there is a short note on what is refresh token and its flow you want you can read there and here is the documentation see if you observe here okay app service dot auth slash refresh token and its payload is like this token and refresh token we need to pass both expired access token and the refresh token to the server to fetch the new access token and new refresh token please make sure to have these property names as mentioned in the blog documentation itself don't change them because those are server properties if you give any another naming properties user cannot understand and they will take these values as null and you will get an authorized response from the server so make sure to have the same properties while posting the data since it is a post endpoint so let's go to our service and create a new service so i'm going into the app service here i am going to create a new method that going to invoke the refresh token endpoint so call refresh token okay and what i will do here i will going to return this dot http dot post and copy the url paste it here and this method should receive some input payload i am going to write like token payload and this payload need to be sent to the server okay and i'm going to written as observable of type any okay now we need to consume this endpoint in our interceptor so what i will do here we are going to write like here we will written like written in the written itself we are going to write the logic restart path service so this this dot earth service call the refresh token and what we were going to do we will use the pipe instead of after receiving the data from our refresh token what i am going to do i will use the switch map of rfjs operator you can see it is added i think rxs operators it will take input test so before going to write any logic here my call refresh token expecting the token payload for that what i am going to create here like constant token payload equal to i am going to copy the properties from i'm going to i'm going to copy the properties from here payload okay and i will say data from my user data they have the same okay and refresh token i am going to pass this payload to my broken endpoint okay so that issue is resolved here now this switchmap receives the new token payload okay here what i am doing i i all refresh token is observable and finally after receiving that observable we are going to written another observable observable nothing but this next dot handle so that it will resume the uh hold request what i mean is my endpoint request is came okay it hits uh interceptor interceptor it finds that token is expected what i am doing i am passing the my api request for now i am stopping altering my api request and calling the another another request like refresh token once my refresh token data is came i need to resume my original request right so that is an observable like this we need to return from here okay so to go this quickly line what i will do for now i will return it dot handle so like this i want written i will change the logic for now to escape from that red line i have written like this and now we will write the logic now this new payload is nothing but the new response from the refresh token endpoint where we have a new access program refresh token the first step what we have to do we need to save them to the where we have to save them we need to save them to the local storage and all this logic i want to hear as well so let me copy and go to interceptor implement it okay this is all of my code what i will do just replace this with new tokens new token new token you know token new token okay i have to copy the awt helper that loads from the separate library so if you want you can write a common method for demo purpose i am not doing that okay let's import converter i think we are good to go this dot hot service okay so what we are doing we are saving our new data to the browser store as well here okay these two links and then i am decrypting my new access token and assigning that access token into my updating my closer info with new data then okay so here next after this line of code i need to resume my original request like a accessing secure endpoint in this my case so what i will do i am going to write same code here itself as well this code copy here once i get the what i can say new access token and refresh token i'm going to implement this same logic so get rid of this line so now i am going to brief brief overview on the logic what we are doing we are checking for the data first step initial next we are checking for the expiration date if it is active we are simply allowing our request to process by adding the authorization header okay and if at all it is expect then what we are doing we are invoking the refresh token endpoint once the refresh token endpoint got the payload we using the switch map what we are doing we are doing all the process that we did for login in the art service here as well okay once that logic is done um we are assigning the new authorization uh our new access token as authorization header and resuming the our old api request okay and that's all and here one one more important thing is call refresh token is also a what i can say interceptor okay intercept sorry is also a api call what i told every api call will hit this interceptor if that the case then what will happen it will go into loop because if we at this point think like this this line is heated means apa ap invoking is started and again in that flow what we will do it will again recom to this interceptor only again it will execute from the top itself for what for the cpa refresh token api at the time what it will do again it's fall into this logic actually this is not required by the refresh token endpoint but we haven't any condition to restrict right so it will go to this logic so if if at all it happens what it will go it will go like a callback hell it will go into the loop never ending loop so we our application gets what we call crashed so at that time to avoid the execution of this what i can say uh interceptor logic on the top of the line we need to write condition like if okay request dot url dot index of refresh token if the url contains refresh token endpoint contains refresh token then what i will do i will keep this entire logic by returning the next handle middleware so here we are skipping the this entire interceptor logic for the refresh token endpoint so that is the one of the main key concept please do remember if you miss it your application is going to be in infinite loop and the application will be in no time it will be crashed so now let's test our application okay i think our access token is already expired let's click on the show produce actually our application is successfully calling the end points but we are getting an authorized why okay i mistake here we are again using the world what i can say old user data access token please replace that with your token that is the reason my api is failing so now if you see now i am successfully getting the 200 okay now if we click again it won't call what i can say refresh token endpoint one minute it is looks like calling always see i made a mistake spelling mistake please remove it okay okay and now test again i think this time it won't call refresh token again and again now it is single time only if you want we will again retest it once after the expiration so what i will do in the application i am going to remove my credentials and refresh my application and i am going to login freshly so since i have active token at the time i don't need to call refresh token the 2d is only calling let me wait for 30 seconds i think 30 seconds will done see now i am able to call refresh token successfully after calling i am able to resume the to-do send point so next time when i click on show to do it won't call refresh token because we have already an active access token so i want to mention that if you search for interceptor refresh token authentication in google a lot of what i can say examples they will show after failing of the what i can say they will allow produce request first if it fails then in the error message like i think something error like is there here subscribe it and there they will catch error if it is 404 they will recall here they will write logic entire logic what i have did they will call inside of it refresh token and they then they will call again to do so instead of doing the refresh token after to do the api is went to the server it is always good to check for the expiration date so so that we can what we can say our application looks more efficient as well as our uh we can reduce one unnecessary to use api call to the server so that's all about the research token integration into our angular application i think we have covered two major concepts here like adding access token as the authorization header and refresh token in functionality into our android application so that's it about everything we can do about jwt authentication in angular i think this video has delivered some useful information to you all if you like my video please subscribe to my channel we will meet you again with the new videos until then signing off
Info
Channel: Naveen Bommidi Tech Seeker
Views: 2,660
Rating: 4.9272728 out of 5
Keywords:
Id: -HwMHTIQFx4
Channel Id: undefined
Length: 42min 58sec (2578 seconds)
Published: Fri Jan 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.