Part-8 | Implement Refresh Token[.NET 7 Blazor WASM JWT Auth]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone Welcome to our Channel so this is dot net 7. Blazer webassembly JWT authentication series okay and this is part 8 of this series and this video is about implementing refresh token now whenever our JWT access token expires we can regenerate the JWT access token using the refresh token okay we are going to store the refresh token into the table for that I am creating a table like user refresh token because user can login with multiple devices right so user can have multiple refresh tokens that is why other than user table I am creating one more uh table like user refresh token where I can have multiple refresh tokens can be stored per use okay so my table contains columns like ID token and user ID which user the refresh token belongs to and the expiration date okay let's execute this script okay and it is successfully executed if I refresh the table here is my new refresh token table okay user controller we have endpoint for login right user login So currently this user login only returning JWT authentication token right so now we have to send refresh token along with the awt access token to the user okay so for that go to our user services okay here let's create a method that going to written as the token okay refresh token so I will create a private method okay and seeing the task and this method going to return the doing nothing but the refresh token okay so let's name the method like generate refresh okay okay so this is the method going to written as a refresh token so return string dot empty for now okay now let's create entity that represents our user table so user refresh token table so go to entities and we have to create a new class okay so let me copy the table name and add a new class in the entities folder okay and let me copy these columns or else let's close this query and open the table okay let me copy these columns for reference okay so public int ID complete string user ID public plane token okay and date time expiration date or refresh token expiration date okay so generally three JWT access token is short-lived rate like 20 seconds or 30 sorry 20 minutes or 30 minutes and refresh working can be like this like two days three days seven days okay so let me clear this preferences and register this table in our database contest class okay oblique PP set the refresh token okay this is a refresh token okay now let's get back to our user service and here and this generate reference token we can have user ID okay as input parameter because we want to store when we create the refresh token along with that we want to store the user ID into our user refresh token table okay now what I will do I will simply use random number generator method to generate a string just like if you recall here we are already generating a random string for hashing rate same thing okay copy this line of codes okay just a random string okay and here I can name it like bytes of token okay and bytes of token okay just I want some 32 characters or bytes of string okay and finally I want to convert that into a base 54 string okay equal to convert dot two base64 dot bytes of token okay so finally here is our refreshed ok now we just need to save it to the DB okay so where you mesh of n equal to user refresh token okay and here are the values so 8 time Dot node dot add this I just want my refresh token valid for three days okay and token we have token value and user ID so user ID now let's save this user ID okay user ID is integer I created string change it okay and now let's save it to the database so I can use a DB context Dot refresh token user refresh token dot add and pass our new refresh token object and finally call save changes async method okay and finally written our token value from this method okay so this method should be consumed in our login async method in this method okay so let's go to JW token response model okay and let me add a new property for our refresh token okay so refresh okay okay now let's get back to the user service and here let's call our refresh token okay generate refresh token and pass the user ID k-u-i-d and finally to the response object as in the refresh token okay that's it so let's check whether we are able to get refresh token along with access token or not okay okay in the Swagger page Let's test our endpoint login endpoint okay so let me give the valid credentials so that I can get access token and refresh token let's check now and I am getting refresh token okay and if I go to database and execute this select query see I'm able to save a token for user ID one zero zero two okay now along with the refresh token sorry JWT access token we need to store our refresh token also into the browser local storage okay so for that let's go to our pleasure webassembly application let me close these files okay and go to UI project and go to our login.tracer so here we are storing our access token right just like that we need to store our refresh token first we need to populate a new property into our JS JWT token response VM model okay so here just add same property that we are getting from the API okay hello oblique string and make first letter caps okay and now I can store it to the browser local storage so wait local storage dots set item string okay and give the key name like refresh token any string you can give and the second value should be our response so cannot refresh token okay now let's check with whether we are able to save it to our browser local storage or not okay so let's click on login okay we are successfully logged in let's check our browser local storage and here you can see access token and the refresh token we are done by providing the refresh token to the Blazer web assembly application now we need to create new endpoint nothing but a refresh token endpoint so on invoke in this endpoint we can regenerated the exped kwt access token and also the refresh token because we have to use or validate the refresh token only once with the server once it is validation is completed we need to generate a new one now let me create a new dto for my new endpoint request object okay so let's create a new class okay I will name it like a new token request dto okay and it will contains parameters like user ID okay and refresh okay okay now in iuser service let's define a method definition okay so for our refresh token endpoint okay so my method I am going to Define like cool and error message comma awt okay sorry new request object okay and your token request and let's give the method name like brand new open SC okay that is our method definition so let's implement this method in our user service okay let's implement the method I think at the bottom there is a method new method definition so here we have to write our Logic for regenerating the access token and the refresh store okay first thing is we need to validate the refresh token is married or not okay to do that I will write like logic testing refresh okay okay so my old DB user token so here I am going to filter the data okay where ID equal to a new token request.user ID and refresh dot token equal to renew refresh token and also check the expiration okay so expiration date should be greater than 8 time dot now okay so if you recall here we added three days right we are checking just like it is expired or not okay and finally first start default testing okay the refresh token not found in the DB then we simply return okay return message like invalid refresh okay and the object will be null okay sorry it should be string changes the type Tuple type okay all right if the refresh token is value I want to remove it from the database because I am going to create the new one okay because it is already used so use refresh token dot remove existing token and call still changes okay now we have to regenerate both access token and the refresh token right so first we need to get the user so we are user equal to what user dot dot where user ID equal to new refresh token ID okay DOT first dot default SC okay I am getting the user information so if we get the user information we know how to create the JWT access token so just go to our login async method okay here we are going to get these two methods from the login and we are going to add it here okay and also the response model and let me copy this entire thing and that's it we are regenerating our new access token and refresh token and here let me give simply empty okay and my mistake here it is not re renew request type it should be our JWT token type the new request type is only our input payload not the output payload okay sorry for that JWT token response okay let's copy this and update in our method definition as well okay that's it we are done with our logic okay now let's add our new endpoint in the user controller okay let's add our new endpoint okay the new tokens the sink okay that is my action method name and it should be also HTTP post method okay and I will give endpoint name like a new token and it must contains our payload type renew token request dto renew request okay so the result equal to a weight user service renew token and pass the payload okay if thing dot is null or empty result Dot error message if it contains a mirror message then we simply return that request okay else tokens are generated good so okay and we are going to return the response resulted Dot aw token response okay so that's it we are done with our end point refresh token endpoint now we have to utilize it on our client side okay so to utilize it first let's our data token must be expired right so what I will do for testing go to login async method and go to generate JWT token method okay go here let's give expiration to one minute okay let's run our API project okay let's get back to our application let me remove the existing token and refresh token a delete delete okay now reload the page here on login page and let me log in again okay we are logged in and wait for one minute then reload the page and check the network calls so let's go to network call I am almost refreshing after one minutes left Let me refresh the page okay here I am getting error and if you check the console here it is showing error like response code 401 okay and if you check the network called here it is failing that is because here it is failing that is because our token is expired okay now we have to handle this token automatically the refresh token API must be invoked okay and it should be refresh our tokens okay so for that let's go to our Laser Web assembly code okay so here our main logic will be written in the custom HTTP Handler here we are intercepting request for adding the authorization header right so here only we are going to invoke the refresh token endpoint as well okay so the first thing is I have to create a we create a method here okay so now what we will do this is the response right once the API call is bypassed here it will be triggered and response will come so here we are going to do some manipulation okay at this response so here what I will do where original response original response means actual request this is or suppose in our case this weather forecast is actual request right so that actual request okay if original response dot status code okay HTTP status code okay is unauthorized okay that means four not one at that time I need to implement some logic here like invoking the refresh token endpoint if it is normal okay any other response or 200 then we simply return the original response so now here our actual logic will be reside okay now what I will do I am going to create a method okay oh private async okay so this method also returns HTTP response only okay as the output and name My Method like invoke refresh API call okay and this method should contains input parameter like our original response okay here we are assigning to this variable right actually API response that response also I should have a input parameter to this method okay so what I will do so it is of type HTTP response message okay and I also want the this actual request means here failed request is weather forecast for example so I want the other forecast request also in spite of it is failed because I want to re-invoke it again okay after calling that refresh token API so what I will do I am going to have HTTP request object a previously failed request object okay so here I will name it like foreign okay now here I have to call the my renew token API call I named it like renew token right refresh token and point call so I want to invoke this API call which is a HTTP postcode okay so that means I need to inject the HTTP client Factory here so let me inject the HTTP client Factor here so private read only I HTTP client Factory okay and let me inject it to the Constructor okay fine fine it is Auto in implemented okay now I have to call the post call so what I will do go to our login component which is a post call right so let me copy the code from here to save some time okay so here these two line line of code first copy here okay so get back to our head custom HTTP Handler okay here just we are creating the HTTP client and here we want to invoke the refresh token endpoint so get the name of our endpoint that is the new token okay so here give it here okay and it it should have payload so what is our refresh token endpoint payload the new token request detail right so we need to create a new model in our uh pleasure of assembly also actually I should have created a class Library so that I can share these common details okay so it is better to have a class Library which can be shared between our API and speculate because I didn't create it now I have to create duplicate types okay now go to view model and here let me add a new model okay and request model VM okay it's payload must be matched to our APA request model detail okay okay now this is the payload I need to send here so this HTTP call But If You observe how we are creating a we are serializing and we are converting as a string content type so copy this two line of code as well okay so go to our custom HTTP Handler and as those two line of code here so here I need to create the model that is nothing but our request model so where the new token request okay new brand new token request object I have created and I will pass it here okay so we are ready with the APA call but payload we haven't created I am passing dummy optic so here what I need I need user ID okay under refresh token you know right refresh token is in browser Locker storage right we can access it just like how we are accessing the uh test this token so copy this line of code okay add it here name it like refresh token okay and here we should change the key what is our key for uh refresh token refresh token refresh iPhone token so give it here okay now I am getting the refresh token so now I can assign it here to this object now I have also want user ID so user ID we will have in our JW token right so we are going to decrypt and get the user ID so for that I am going to input the awt token to this method this method will be called here right so here we have already accessing the token so I am passing it here so now I need to decrypt this so can I get my clients if you recall in the custom authentication provider Handler we have methods for decrypting our JWT token so now we will move these two methods to a separate file something like utility okay so that it can be shared so let me create a new file utility okay to this file uh let's move this book methods and make this main method public okay now first update in or custom auth provider here okay here utility dot okay so now I can use this method utility method for decrypting the clients okay so go to our custom Handler okay and here where user clients equal to utility Dot or prime token method call okay now I got clients as well now I can assign the clients to this user ID so user claims to list okay dot where DOT type equal to sub if you go to our API user service where we add the clients to our token okay here I am adding climb rate here sub means the user ID okay subject ID so I can use the climb type sub let's get back to our custom Handler and compare it okay then select the value that will gives the user authenticated user ID okay convert Dot 2 in 32 underscore value DOT first dot default okay those were so good so we are ready with the payload and prepare the payload for my refresh token endpoint okay so here let me change the variable name response to refresh token respond okay now here also I need to check but I need to check if refresh token response dot status code equal to equal to 200 okay here for me it's only matter when it is success if you check in the above case here it is only matter when is unauthorized okay so if it is success then that means we are getting new pair of awt token and the refresh token so now what I will do go to login component here what is what we are doing on login successful login we are getting the token response rate same response we will get here as well so after getting we are storing it to access token and refresh token and we we are also refreshing the our custom auth provider so copy these line of code from here okay and add it here okay now here change like three generated okay okay for our understanding and here response is refresh token response okay now let's import the namespace okay and here change the refresh token okay now here we are restoring with our new JW token and access token into our browser storage and here we need to read only what is the service I need to inject authentication State provider okay or here authentication State provider okay import the namespace now here I need to inject the Authentication date provider let's copy this variable okay and assign it okay and here change it to underscore or state provider okay so till now I am good if I if refresh token endpoint also fails are refresh token we passed in the payload is invalid token if any other other than 200 if we get any other then we simply return original response means already here failed rate for our case whether forecast we are inputting rate again if refresh token also failed simply weather forecast error only we will directly return okay now after successfully regenerating our refresh token and access token we have to invoke previously failed request okay so for that what I will do Here I Am inputting original request right so original sorry original request okay so I want to remove the expat JWT token header in the original request for over that let's copy these okay let me add it here okay and again duplicate it one more day and here instead of add first I need to remove I need to remove the old one okay hold access token header I can simply remove this and again add either new refresh token so that is regenerated tokens Dot access now I need to invoke the API call so after invoking the apical we can use this base dot sandlasync method okay so I will call it here so it will automatically reinvoke the already previously failed request see how carefully we are handling we are invoking the refresh token after success of refresh token we are again reinvoking the failed request okay now here request will be the original request original request and we need to input the cancellation token also Okay so here cancellation token is there right same cancellation token I can input here for this method as well okay with lengthy logic right but you can understand it slowly now I am good now I can invoke this method here when I got an authorized exception so invoke refresh call okay original response comma request will be our original request 100 token and cancellation token okay that's it we are done with the refresh token and point logic so let's again go here one more thing I need to do whenever I am calling this refresh token it should not go too into this Loop if it should not go to into this loop I have to terminate here so here I have to write logic should not interrupt the refresh token endpoint also just like registration and login if you don't write this condition uh your API call keeps on go to infinite Loops okay okay so let's check the logic briefly injected HTTP client Factory and authentication state provided as we required and here we are checking if the HTTP call is a refresh token sorry all should be a new token and name it like renew tokens right train your token okay if the renewed to okay then normal flow we no need to interrupt it okay so next for example I am invoking whether forecast API so here I am adding weather forecast uh authorization token because weather forecast is a secured endpoint okay if the okay if the API call is successful then no problem we directly written if we get another ID 401 then we are again bypassing the logic so what we are doing here we for to this method actual response and requester in inputting means whether forecast response and weather forecast requester input I am just explaining like a weather forecast for every security API this logic will executes okay so first here what I am doing I am getting refresh token and I am getting clients of my JW token because I need to prepare the refresh token payload okay that is refresh token and the user ID and here I am simply calling the refresh token endpoint if it is successful then I am again restoring the new awt access token and refresh token into the browser local storage and also I am refreshing the authentication state of our application okay so up to here our invoking refresh token endpoint is done next here what I am doing I want to invoke already failed weather forecast API so I am inputting original request as input right so I am removing the expired authorization header I am adding new authorization header with new access token and finally invoke in the API okay before testing the refresh token endpoint I'm I done two mistakes here I forgot to return the final API call pre-invoking the original request right original apical I should return it here don't forget to return this one and also in the user service in the Reno okay endpoint here I am checking ID of the refresh token not ID it should be user ID okay and one more mistake this method should be written here okay totally I forgot written here and here as well okay now let's test our replace token endpoint okay let me login now let's wait for one minute okay almost one minute is done Let me refresh the page and we are getting data if I check Network calls see here weather forecast failed two two or not one another ID immediately the new token invoked APA call and payload is our new access token and refresh token again immediately our failed API is invoked with new authorization header so all the things we handle inside of our custom delegate Handler okay so that's all about implementing refresh token in Blazer webassembly application next we are going to do logout implementation thank you so much for watching this video I hope this video delivered some useful content to you all if you like the video please do support by subscribing to the channel and please don't forget to like and share the video soon we are going to meet with new content until then signing off
Info
Channel: Naveen Bommidi Tech Seeker
Views: 1,903
Rating: undefined out of 5
Keywords:
Id: msk7jLPRbj8
Channel Id: undefined
Length: 44min 27sec (2667 seconds)
Published: Wed Jun 07 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.