Refresh JWT with Refresh Tokens in Asp Net Core 5 Rest API Step by Step

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Good stuff. Thank you for the share. I am watching this now as I would like to work it into one my blazor server side projects.

👍︎︎ 2 👤︎︎ u/nanjingbooj 📅︎︎ Jan 25 2021 🗫︎ replies
Captions
hello friends thank you for watching this video i am muhammad and i will be showing you today how to add refresh tokens to our jwt authentication to our asp.net core rest api some of the topics we will cover are refresh tokens some new endpoint functionalities as well as jwd tokens please like and subscribe if you like this video this is part 3 of our rest api journey we will be basing our work on our previous to do rest api application that we have built in our last two videos links to those videos will be in the description down below as well on the upper right hand side corner you can follow along either by watching those videos and bringing the application with me or you can get the starting source code from the description down below before we start implementing jwt refresh tokens we will examine how refresh tokens will actually work by nature jwt is a clo song it's a short lived token and the shorter the time that it's lived it's safer and for us to get jwt tokens there's gonna be two ways the first way is gonna be if we have a user and again gonna logged into the server every time they log in they get a jwt token in return and this jwt token will last for example let's say five minutes so after this five minutes is over the user have to relog in again and do the same process all over again this is not a really good implementation because in every five minutes we're gonna request the user to input their user their credentials again and login and we can see for example instagram twitter all of these big companies don't have that they have those functionality automatically enabled as refresh tokens in order for us to get tokens every time our previous token expired the next way for us to get always jwt token is to have refresh tokens so what happens so instead of always doing this process again so within the first jwt token we're gonna have here a refresh token with it and this refresh token is gonna be responsible to doing this process for us so it's gonna it's gonna automatically regenerate the token and it's gonna automatically send it back without even the notice the user noticing this process will happen automatically in the background without the user ever knowing so what is a refresh token a refresh token is anything we can make it anything we want it can be a string it can be a grid an id anything we want the longer the better in order for us to make it more secure so why is it important to have a short-lived jwt token the main reason is security so let's say for any reason our jwt token has been compromised jwt token have an expiry date and this expiry date is only gonna be for example five minutes so after those five minutes the user will uh anyone who stole our jwt token we're not gonna be able to use our application so let's say for example we have a user and this user has lost has taken for example from the server a token jwt and this token has been lost and since it's already last for five minutes and if someone else takes it let's put someone with a hat and if that someone with the hat takes it it's only gonna be for five minutes so they cannot use it again against our server it will not work because it's short-lived so this user here will only have it for five minutes so this is why it needs to be a short-lived token and it's always better for security now let's examine how actually jwt token works so first of all this is going to be let's specify it in a way we have a user and we're going to have a server and the server is going to be connected to a database and the user will have let's say local cache in the browser and we're going to have all of these to summarize the request that we have so the first request is going to be from the user to the server as a login which is good then the server let's put your server okay so the server is going to return to us after it has authorized the user jwt with refresh so right now the user have to make new requests so this new request is going to take the jwt as well as the refresh the server will do all of the work and then it's going to turn back to us the response the user at this time within the local cache has the jwt saved and the refresh token saved so let now let's say for example the user wants to make a new call so the user wants to make a new call it goes here let's make this different color so we can understand the differences so once the user let's remove this first okay so this user here now who wants to make a call let's say for example he wants to get all of the products for example products so in order for the user to get any call or any products for example they need to be authorized so the server is gonna check the jwt token check the token once the server noticed that the token has expired it's gonna return back to the user it's gonna return back expired notice expire token the user although enduring all of this thinks that there's only one request happening which is get products so what's going to happen right now with the api the api is going to send a new request to the server which containing the token and the refresh token the server is going to do the checking the verification and then once everything is back on track it's going to return back to the user a token a brand new token and a brand new refresh token perfect so once we have that the user the user thinks okay they have a new token they're gonna send back for the products products the api will see that everything is right that the token has not expired and the user is authenticated and this can return back the response so just to do like a quick summary as we can see right now from here that all of this and all of this processing from the user side and from the server side all happen within one request and the user thought everything has been smooth uh smooth process so they didn't think that oh they have to log in again didn't know that they had expired the refresh token that functionality took take care of everything the user might have a bit of a delay like maybe a half a second or a few milliseconds delay until this entire process happen but it make it waste more than asking the user every time to log in again so this is why it's really important for us to implement a jwt refresh token when implementing it with an api so let's get started we'll first start by updating our startup class by making the token validation parameters available across our application so how do we do that we go to our startup class we go to our token validation parameter let's take all of these and let's create a new variable we'll call this variable token validation params equal and we paste the information that we have gotten as we can see it requires a key so first let's take this we'll add it to our token validation parameters we'll take the key and we'll paste it before the declaration perfect so once we add those let's make sure that our application is still building by going to the terminal and typing dot nut build and we can see it built succeeded after that what we need to do is we need to update our generate jwt token in order to shorten the expiry time frame how do we do that we need to go to our controllers auth management and let's scroll down to our generate jwt token function that we have created and instead of making it six hours we're gonna change it to seconds at seconds and we're gonna make it every 30 seconds the token will expire this is only for demo purposes usually in a live application what you can do is you can make it every five to ten minutes so every five to ten minutes the jwd token will expires and it needs to be regenerated which is great so the next step for us is we need to update our auth results so within our configuration folder within our auth results we need to add a new refresh token so we can return it back to the client so we'll add a new property it's gonna be a string and we're gonna call it refresh token great then we're gonna be add a new class within our request in order for us to be able to accept those requests token so basically whenever a refresh token is going to be expired the client will do a new call to our api and they're going to be sending with them an object when within that object is going to be our refresh token request and that is going to contain two variable token and refresh token so in order for us to add those we need to go to models dtos under request we'll add a new class and this class will call it token request and basically it's going to contain two properties it's going to be a string which is going to be the current jwt token that the client has and the other one is going to be the flash token that also the clients get string and call it refresh token and let's add some attributes so this has to be required and let's fix the references and we'll copy this and we'll put it under on the second property perfect so now we have added those the next step is to add a new model in order for us to let entity framework know where are we gonna be storing those refresh tokens so we are able to map them so in under the models folder outside the dto that's the new class and this class will call it refresh tokens okay good so the next the first thing we're going to add is going to be an id it's going to be of type end the second thing we're going to add is the user id of type string because basically we're going to be utilizing the asp.net core identity and that id is going to be of type string actually it's going to be of typing with but for simplicity reason we're going to be using string the third property is going to be also a string which is going to be token the fourth is going to be also a string which is going to be of type what's going to be the name jwt id so basically this is the id of the jwt that this refresh tokens belong to and then we're gonna add another boolean which is gonna see if it's used or not uh is used and another boolean which is gonna be is revoked so in case the user revoked all of the access token this boolean will be updated and then we're gonna add the last two items is gonna be type datetime date time it's gonna be the added date so basically the date that this token has been created and we're gonna also add the last one also of type date time and we're gonna be specifying the expiry date of this refresh token because basically refresh tokens are long lift tokens when jwts are short-lived tokens so the jwt token usually last as we mentioned before five to ten minutes on a live application where different cases the refresh token will last for example a few months to a year so it's always best to for example make the expiry date of a refresh token six months expiry date and we'll just fix the references and they're ready perfect so after we do that what we need to do is we need to link this table to our asp.net core identity table so how do we do that since we are using entity framework it's going to be very easy for us to do that all we need to do is add a foreign key to that table so first of all we define the property which is going to be using identity user we're going to call it user and it's going to be as simple as setter and gutter let's fix those references and then we're just going to add an attribute to define the foreign key and once we have that all we're just gonna define on which type of property we're gonna link and it's gonna be on the user id perfect so now let's fix those references and let's make sure we saved everything and let's try to build the application make sure everything is still building perfect so after we have added our model the next step will be is to update our api context so db contact so how do we do that we're going to go to our data folder we have the apidb context underneath this we're going to add another public virtual dbsat and we're gonna call it refresh tokens and we're gonna call it refresh tokens very easy and it's gonna be get and set perfect so right now what we did is we created our model and now we have added our api db context and the last two steps first of all we're gonna create a migration and then we're gonna implement this migration and then we're gonna check it within our database so how do we do that we go back to our terminal we type.net ef migrations add and we'll give this migration a name we'll call added refresh tokens table enter this can take five to ten seconds perfect and then what we need to do is we need to implement those migration scripts that have been created if we see under the migration folder the flash token table with all of the functionality or default parameters that we gave it and how do we implement those changes to our database by simply typing.net ef database update this will also take 5 to 10 minutes i have a 5 to 10 seconds sorry after we do that we can see stun and we can verify that by opening our db tool i'm going to be using db beaver okay great now let's open the app let's first close this we don't really need it now yes and now let's open a new one basically we connect our current application next and it's gonna be on our desktop and under to do we have app.db and let's test the connection perfect and now let's open it and right now once we open the tables we can see we have a new table here called refresh tokens and we open it right now you can see there is no data inside of it it's completely empty perfect so once we have done that the next step for us is to create our new refresh token endpoint but before we do that we need to add some pipelines to our auth management controllers so let's go to our auth management controller and let's go all the way to the top the first thing we're going to add is the token validation parameters that we have injected so private read only token validation parameters i will call them token validation params and let's initialize them within our constructor basically once we add it as a singleton the dependency that the i the dependency inject that we have will automatically pick it up and it will automatically figure it out how it's going to inject it within our constructor in this controller so let's add it here token validation parameters i will call it token validation params and then it's going to be as simple as talking validation parameter equal token validation params perfect the next step we're going to do is we're going to add our db context so again private read only api db context we're going to call it as simple as api db context and that's fixed references perfect now let's add it again to our as well it's automatically injected for us through the dependency injection and we're going to call it api dv context and then it's going to be simply linking it up api db context equal api context perfect so once we inject the required parameters we need to update our generate token function to include the refresh token so let's scroll down to our generate token function and the first thing we're going to do is we're going to change the initial the definition of this function so the first thing is we're going to make this function async because we're gonna be connecting to the database and writing data to our database second the return type is gonna change from a string to an object so first we're gonna make it as a task and then the object that we're gonna return is the auth result object perfect and now what we need to do is we need to update the rest of the function so the first thing we're going to do is after our token has been created let's initialize the new flash token and equal new refresh token and let's fix the references before we continue perfect and now first we're gonna start by adding the jwt id so jwt id equal token.id so this token here is coming from the previously defined jwt token and the id is here perfect the next one is we're going to see if this is used or not is going to be false so is used equal forced as well as revoked equal false then we're gonna be adding the user id equal user.id and then we're gonna add that datetime added and since we're gonna be utilizing across different environments it's always best to use the utc time so we're going to put a date again with date time dot utc now then we're going to add an expiry date and for this refresh talk and the expiry date will be six months from now so we're gonna put date time dot utc now dot add months and we're gonna make it six months perfect and then lastly we're gonna be generating the token the refresh token that we're gonna be using so token so we can have the refresh talking anything we want it could be a string it could be a grid it could be a combination of two and that's what we're gonna do we're gonna make it a combination of two so first we're gonna create a utilize a function called random string and we're gonna make it of 35 characters as well as we're gonna attach to it but it's always better to make this refresh token as secure as possible new grid so let's create now the random string function so after this we'll create public let's make it private string i'll call it random string and it's gonna take int it's gonna be the length and then we're gonna utilize the for our random function from c-sharp equally new random and then we're gonna put all of the characters that we want i have this already set aside so i'll just copy paste it perfect the next one is we're gonna just return now the string using the random one so put return new string enumerable dot repeat chars it's a very simple string generator that length so we defined the length that we want dot select random dot next and we'll make a toilet perfect so it's a very simple function first we created a random generator from t sharp then we define the characters that's going to be within our function uh within our token sorry within our string and then basically we just initialized the new string used a new rubber repeat we defined got the characters the length and then we selected the random random characters from within those charts and inputting them in order and then we put them into array and then we return them great so after that what we need to do is let's go back to our generate jwt function and now let's save those refresh token our database so await underscore api db context dot refresh tokens dot add async add async and we're gonna pass the refresh token perfect and then what we need to do is as simple as api db content let's save it changes async so why did we put both since we're using entity framework core so basically the first function here we just added this object that we have created into the refresh token table in our memory and we didn't commit anything to the database when we put save changes entity framework will take all of the changes that we have in memory and generate the sql script and then it will save it in the database perfect so since we have also updated the return type we need to update the return here so instead of directly returning the string we're gonna be returning a new auth result and we're gonna be giving it the requirement so we're going to give it the token it's going to be the jwt token that we generated before we're going to give it a success equal true because it's successful and we're going to add the refresh token that we have generated equal refresh token the token perfect now the next step for us is to update the return of the other two functions in order for us to make sure that nothing is broken because basically here we're utilizing directly the string and then creating our own responses so in order for us to do that instead of returning this first this is gonna need to be awaited because it's gonna be it became async and then this one here we can just delete everything from the inside and return the jwt token similarly to the other endpoint which is the log with just a login we fix the register we need to await the generate token function and we need to delete everything from within the okay and just return the jwt token object perfect so once we do that let's try to build our application make sure everything is still working let's turn it dot not run and now let's test it out okay so now let's open postman and within postman let's create a new request this new request gonna be a post and it's gonna be on https localhost port 5001 forward slash api let's see what's the path for this api so api auth management api forward slash of management forward slash register let's register first and the registration as we said let's see what the registration is going to take it's going to take user name email and password so let's add those so under body row we select json perfect and let's create this new json so it's gonna be as we said username let's give it our email for now it's gonna be muhammad at email email 111.com we're going to give it an email address it's going to be the same let's copy this one and we need to give it also a password which is also going to be something simple we're going to put it pass word one one two one okay let's send this okay perfect we have an error what's the error dependency injection token validation parameter by attempting to activate it so let's see let's go back token validation parameter token validation parameter okay let's make sure that we have everything set in our startup class so let's go back to our startup class okay so we added it but we didn't add as a singleton excuse me that's my fault so here what we can do we can just add services dot add singleton and just pass that token bottom token validation params as simple as that let's stop it again and now let's run it okay it's running let's go back to postman and send this request perfect now it's working because i forgot to inject the token validation parameters okay so once we have done that uh we can see that we got our token as we get as well we got our refresh token which is great let's try to log in so let's copy this one copy let's make a post i think it also is going to require a body of type json and it's going to take an email as well as a password let's copy those okay a bit faster let's see if it's still working user name field is required oh sorry so this one needs to be long and not this is what happened when we copy paste now let's try it perfect we got the token we got the refresh token great so now we made sure that both of our uh registration and login are working the next step is to actually start building our own actions called refresh token so let's go back let's stop at this application and let's create a new action this action will call it under the auth management controller this action we're gonna call it refresh token so after the login so the first thing we're gonna make it as a post we give it the attribute post the second thing we're going to give it the route directory so route it's going to be refresh token perfect and then we're going to define it so it's going to be public async task of i action result i'm gonna call it refresh token and it's gonna take from body a token request that we have created earlier and we're gonna call it token request perfect so the first thing we're gonna do is we're gonna make sure that the object that we got is valid object so if model state if i can type okay perfect dot is valid we can assume else we're gonna return an error so let's return a bad request and we're gonna call the new uh let's use the new registration response wait and to be honest we need to have our own bad response but for now to save time let's utilize this one and basically all we need to do is we need to add our errors basically it's going to be a list of string and we're going to be defining the first item in it so it's going to be as simple as and we're going to put it in valid payload perfect and then we're going to add the success to false so now once we have done that now let's continue in the case that this actually work so how do we do that let's first create a function called verify token so verify token and we'll pass that token request to it so once we have passed the token request to it let's create this function because currently it doesn't exist so here let's create a new function called uh verify token so private async it's gonna be task it's gonna return same auth results because it actually work we're going to generate a new token so auth result verify token and it's going to take the token request that got sent to us token request perfect so once we have that the first thing we need to do is we need to create a jwt token handler in order for us to start doing the verification on the token that we have received so far jwt token handler equal new jwt security token handler and since this function is going to be prone to generating errors and crashing so the safest way to do that and safest way to utilize this function that we're going to be adding is having it inside the try and catch block so let's create a try and then let's add the catch as well and exception let's put it ex and we'll return a null in case something goes wrong let's fix the references except i think i mistype it so it's gonna be perfect so right now after we have created our try catch right what we need to do is we need to have our main um verif verifier which is going to be taking the token from the token request and making sure that the string that has been passed to us is actually a valid token and not just a random string so in order for us to do that we'll create var new variable we'll call it verified token or we call it for example token and verification so it's gonna go to a different step vacation okay equal jwt token handler dot validate token and basically it's gonna take the token request dot token and we're gonna pass it down token validation params that we have injected in the beginning and it's gonna out a validated token out for validated token and we're going to close it so basically this function here is you're going to be utilizing the jwt security token handler it has a function called validate token which is going to make sure that that token that we have is actually a jwt token and then we're gonna pass it the token from the jw from the token request we're passing in the token validation parameters and now if you look right now at the taken at the token validation parameter in the startup class we can see that those parameters that we are sending are these things here which is the security key which has got uh encrypted by uh and different time is if it's validated for lifetime the audience the issuer and all of these different parameters that we have so when we're injecting this into different part of the application we are re reutilizing it within the jwd token handler to verify that our token actually belong to our application based on the configuration that we have selected so once we have done that and now the next step for us is to actually see if this so just to stop uh to do a step back so right now within this function right here we just validated that the string that we have isn't actually a jwt token the next step for us is to check if this jwt token that we have has been encrypted using the encryption that we have specified so in order for us to do that it's going to be a very simple as well we're going to be using an if statement we're going to using the validated token that it has been generated for us and we're gonna see if it is a jwt security token and let's initialize it and then within this if statement we're going to see let's do var result equal jwt security token and we're going to go to the header and then we're going to go to the algorithm and then we're gonna check equal security algorithms i think we use the hmca let's see hmac sorry 256 and string comparisons it's gonna be invalid culture perfect so let's add this and once we have this what we need to make sure is if the result is true or false so basically this function will return a bull to check if these if the token that we have is encrypted with the security algorithm so if result equal false we're gonna turn on because it doesn't match so this was our first level validation validation one this is our second validation validation two and now we're going to do the third validation there's going to be a roughly around 7 validation i think validation 3. so validation 3 is we're going to check the expiry time of that token we're going to make sure that the token that we have is still valid within the expiry time so var utc expiry date we're going to call this variable equal long dot parse because basically we're gonna we're parsing a long time of so basically the token is saved as utc time and d2c time usually is an integer it's the number of seconds from the 19 from first of january 1970 till now so usually it's a very long string so this is why we utilize the long one and we're going to use the token and verification dot claims dot first or default and we're gonna basically match it on the expiry date so it's gonna be x it's gonna be the lambda function the type equal equal jwt registered claims names dot expiry and then we're gonna utilize the value perfect so again as a small summary we utilize long because we're using the utc time frame and then from the token invalidation we went to the claims and we got the first one that actually matched the jwt claims name which is going to be the expiry date and we got the value for it so after we do that the next step is we need to convert this time this date that we have to an actual date that we can compare with so how do we do that let's create a function it's going to be we're going to call it unix timestamp to datetime so first we create a variable we'll call it x expiry for example date it's not going to be unix timestamp um we'll create a function unix timestamp date time today time perfect and we're gonna pass the utc expiry date now let's create this function it's gonna be also a very simple function let's scroll all the way here perfect and this function is going to be also private it's going to turn date time we pass this one the name of the function and it's going to take a double and the double is going to be the unix timestamp or we can use a long because actually we made it as long so unix timestamp perfect and within this function we're gonna utilize system date so date time for we're gonna call it uh date time val equal new date time and we're going to initialize this date time for the 1917 january 1st 1917 so it's going to be 1971 1 and that's going to be 0 zero zero zero zero i think it's four zeros one two three four yeah four zeros and then lastly what we need to do is we need to add what what type of time that we wanted to compare with it's going to be utc so we'll put system so put date sorry datetimecoin.utc utc perfect after that it's going to be a very simple comparison we're just going to add the number of seconds so it's going to be date time to the datetimeval equal datetimefile dot add seconds we're adding the seconds from that time and we're gonna add the unix timestamp unix timestamp and then we're gonna convert to local time okay perfect and we're gonna return this so return date time val day time far perfect so once we have done this now let's return back to our verification so we are already on verification number three which is checking the date time span date time span and now let's check it so once we got this the next step for us is gonna be i think we have some kind of an error here let's check because i'm getting these warnings it means that it's the warning it's expected oh within closets and it's causing an issue okay perfect so let's go back to the function so the third validation was to check the expiry time frame and in order for us to do that what we need is simply going to be if else statement so we're going to put if expiry date is bigger than datetime.utc now we're going to compare it on utc so if it is bigger it means that this refresh token has not yet expired and the user well we can let the user uh get a new one but if they if the identity if sorry if the token has not expired there is no need for us to generate another one but it all depends on the scenarios that you want to use so let's return the new auth result and again it's only going to return errors so firstly the success equal false and the errors is going to be equal a new list of strings string and let's define this it's gonna be uh we're gonna make it token has not yet expired simple perfect so after we've done that the next step for us is to check if this actual token exists on our database so this is going to be validation for so how do we do that basically we're gonna check against our api db context so far gonna call it stored token equal await you utilize the apidb context dot refresh tokens perfect dot first or default and we're gonna check this refresh token based on the actual token so x dot token equal token request equal equal sorry token request dot token okay great so once we have got this we need to make sure that why this is giving us this oh okay we need we didn't use the async one which is fine okay and i think this one requires link perfect so what we're gonna check right now if this token is empty or not so if this value is null and so this means that this token does not exist in our database we're gonna return back to the user that refresh token does not exist we shouldn't really give a lot of information only we need to give the bare minimum information so the users will know what's going on but we shouldn't really give a lot of information so first we go to if store token equal equal null null we're gonna return let's copy this faster and paste it and instead of this one we're gonna say token does not exist perfect so validation number four it's gonna see we're gonna check if this token exists so since we already checked here that this token sorry if this token is used so since we checked that the token already exists now we need to check if this token has already been used before so validation number five it's gonna be if store token dot is used so the revokes gonna come after so if it is used we're just gonna return an error saying that this token has been used token has changed this has been used simple message then we're gonna do validation number six which is gonna be if check if it has been revoked or not start talking dot is revoked we're going to return an error and we're going to talk and has been revoked perfect so after those what we need to check right now we need to check the jwt id so how do we do that it's going to be also we're going to utilize the claims in order for us to get it so we're going to use var i'm not sure what i call it let's see we call the token and verification perfect so far we'll call it json token i id equal token and verification dot claims dot first or default we're gonna utilize the type and the type equal equal jwt registered claims names dot gti perfect dot value and we're gonna close it i don't need to close it it's already closed okay so after that what we need to do we need to make sure that this gti matches the id of the refresh token that exists in our database so let's go let's do this equal validation 7 validation 7 and here it's going to be a simple if statement so if start token dot jwt id equal equal jti so it's not equal jti jti so we're gonna return a simple error with token does not match we don't need to give much more information doesn't match perfect so after that we made sure that all of these validation and we make sure that everything has passed right now we need to update the token that we have because it apparently it's valid and we need to generate a new one for the user and because this one has already been valid so we can mark it as been used so how do we do that it's also very simple so right now we'll make update current token so how do we do that basically we just take the store token that we have got before store token dot is used it's gonna be true so in the future if someone else tried to use it it's gonna be already used and then we're gonna update the database so api db context dot tokens refresh token sorry dot update and we're gonna pass the stored token as simple as that and then we're gonna just await and we're gonna use the apidb contacts to complete basically to save the changes async once we have done that what we need to do right now is we need to get the user that is logged in based on the information that we have from the jw token that we have and then based on that user we're gonna create a new jwt token which include a new refresh token as well also how do we do that also very simple we're going to utilize the user manager class that we have defined it before so we call it db user equal await underscore user manager dot find by id where is it filed by id okay and then we're gonna use the store token dot user id because we already have it and then after that we're just gonna return a simple await generate token right jwt token and we're gonna pass that db user that we have perfect so this is a simple validation for our jwt token so let's change the name from verify verify and generate so it will reflect what we're doing so verify and generate token so we did the validation so this is gonna be an await and it's gonna return for us a uh object so how do we how do we do that it's going to be as simple as var result equal the function and then we're going to return it so first we need to make sure that if it's null or not so if result equally equal null maybe something went wrong maybe the user is not active anymore could be different reasons so if it's null we return a bad request let's copy this and paste it here and instead of this error what we can say inverted tokens and in case everything goes well and we make sure that the result has been generated successfully we return okay with the result inside of it perfect so this is a simple function which is called verify and generate tokens this function basically we do seven types of validation on the token that we currently have and those seven level of validation goes firstly to verify if it's an actually valid jwt token format then it actually check let's see let's add these commands here so validate jwt token format then it actually validate the encryption validate encryption algorithm and then it validate the expiry date and then it does the db check validate existence existence of the token and then validate if it's used or not and then validates revoke and verify the id validate the id and lastly generate a new token which is that update and here is going to be generate a new token perfect so now since we have all of this let's save make sure everything is saving and now let's build make sure the application is building successfully perfect i'll let's run the application.net run now in order for us to verify that everything is working we're gonna do four types of tests first we're gonna log in and uh we're gonna use the jwt token directly and to to get a new token and that should fail because the time stamp is less than 30 seconds the second time is uh the second thing we're gonna do is we're gonna take that jwt token and wait after 30 seconds and try it again see if we get the new token and then we're going to use the same token over again and see if it's actually going to generate one for us or giving us a message that has already been used so let's go back to postman and as we can see here we logged in and we got a token so let's try to log in again first let's create the endpoint before we log in so we can save time so post let's copy this one uh what did i name the endpoint i think it's called refresh token you had a flash token so we'll call it refresh token and it's gonna take a body row of type json and it's gonna take the refresh token as well as the token so let's try to log in first perfect now let's copy paste these and let's paste them here and try to log in directly it should give us invalid because the token did not expire yet now let's wait for around 30 second let's wait for another 30 seconds let's wait for testing we can make it 15 to 20 seconds but let's see right now i think we need another 10 seconds let's try now still sets us token does not exist okay so we have an issue so token does not exist so let's check the validation of our functions on the token does not exist so token validative token exists token does not exist so one is trying to get it directly from the database it's not nowhere else first of all let's make sure that our database is actually saving those tokens so let's open db beaver and let's refresh view data okay we have information and let's check what's the token start with that we have the refresh token start with 0 fx so we have zero of x so it does exist i wonder why what happened so let's check again so first or default so we're checking that token against uh oh sorry we need to check against the refresh token okay my bad so let's stop it again and let's run it okay now it's running correctly now let's check if it's actually working so let's go back to postman and send it again and we can see it generated for us a new refresh token perfectly so now let's take this one again and try to run it in less than 30 seconds it should give us first before we do that let's run this again it should give us as this token has already been used token this has been used and now let's take this one paste it has not expired yet so let's wait 30 seconds perfect so just to reset everything and make sure we go through our testing scenario all over again let's try to log in with the same account login we got a new refresh token let's copy paste these so we'll copy them and let's paste them here and now let's send it it should give us it's not expired which is the expected answer let's wait for 30 seconds now and after that we're gonna run this one again it's just tell us that has already been used perfect we have requested it and we got a new token as well refresh token now if we click on this again it should tell us that has already been used perfect and right now we have passed all of the testing that we have which is great so just to do a quick summary within this video what we did is we created we updated our apis in order for it to support refresh tokens so we updated the functionality uh within our auth management controller we added a new endpoint we added some models as well as dtos and we updated our database to have a new table which is going to be storing all of the refresh tokens i hope you really found this video really helpful and please like share and subscribe to watch more videos like this thank you very much for your time and see you next time or one more thing the links to the source code is going to be available in the description down below thank you very much
Info
Channel: Mohamad Lawand
Views: 9,838
Rating: undefined out of 5
Keywords: asp.net core, jwt, authentication, restapi, rest, api, beginner guide, step by step, sqlite, postman, dotnet 5, asp.net 5, ef core, code first, refresh tokens
Id: T_Hla1WzaZQ
Channel Id: undefined
Length: 66min 15sec (3975 seconds)
Published: Mon Jan 25 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.