Stay Fresh: .NET 7 Web API Refresh Tokens 🌊

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends let's Implement refresh tokens today but first maybe let's answer the question what actually are refresh tokens well I asked gpt4 about that so let's have a look a refresh token is a long lived token used in authentication systems to request new short-lived access tokens when they expire now this approach improves security by limiting the validity of access tokens reducing potential damage from token compromise and allowing for easier revocation when necessary now short-lived means that for instance a typical Json web token should expire after an hour for instance but the refresh token then can be used to get a new access token a new Json web token as we will do here in this example and this process again as it says here is more secure than issuing long lift access tokens because if an access token is compromised it is only valid for a short time and additionally we can and also revoke the refresh token at any time if something is fishy and then I ask GPT just for fun could you explain refresh tokens to me as if I'm 5 and then it says a refresh token is like a special key that helps you get new keys to open a door when your old key doesn't work anymore and this makes sure that even if someone steals your old key they can't use it for a long time alright everything's clear now so now let's implement this thing I already have this little application here check out the older videos if you want to know what is going on here but it is not really necessary if you want to have a look what we are doing here is we simply register a user we can leave it at the default values string string and then we log in also with string string and with that we get a Json web token and then we use this Json web token to authorize the user here so we send an authorization header with this request here for instance and only with that token now we are able to get the username which is string in that case but if we log out for instance and execute it says 401 we are not authorized and now additionally in this tutorial here we want to add refresh tokens they have nothing to do with Json web tokens in essence so the implementation is different here this means in our example application what we have is for instance our user model and with the authentication controller I know fed controller shouldn't do that let me just remove this you can see that here but it's about learning here right so in this fed controller we are creating this token and this is how that's done using an algorithm and so on but refresh tokens and also the claims here that's important right but refresh tokens are in essence just a string of random character so there are no claims in there it does it can be anything it could be just five numbers or a really really strong with random characters and this is what we're going to do here and you would also store the refresh token in the database again we're not doing this here we are using an Essence here in the user service just a static user in essence not here where is it again in the auth controller of course so here the static user right so this is what you're going to do here but in a real world application of course you would use a database if you want me to do that and show you that please tell me in the comments then maybe I can create another video for you but for now here you would or we would just extend our user model and then return the new refresh token with this user model but before we can do that we need another another model and that would be the actual refresh token so let's add this thing and we do that by adding a new item called refresh token all right and here now we say this is simply a string which is the token and this is actually required so let's do that and we get no warning here then we wanna set a created date like that and by default we can actually set this to daytime now and the last thing already in this case is the expires date almost expires also a property no default a value here but what I also wanted to mention is that to be able to revoke a token for instance what you can do in a real world application is to also set an ID here and a flag that this thing now is revoked and when someone is trying to use an older refresh token and you have some logic in your backend that is recognizing that then you know that probably something fishy is going on here so maybe you want to do something then with that all right so this is the refresh token next the user model now gets this refresh token so here we add a property again a string which is the refresh token let's set this to string empty by default then also date time for the created date of the token because again we will return the refresh token but then we would store this in the user object all right so that's that and then also the expiry date token expires something like that all right and with that now we go to the Earth controller and here now you see we've got this login Method All right so we are checking within this request we've got this user dto username password all right and this thing then checks if the username is actually there so here in this example again we only have one static user so that's that I just wanted to show this in an earlier tutorial that with that we can check if the user is actually here and then we're using bcrypt to check if the password is valid and for that we have stored a password hash in the user object and with beefcrypt then we are trying to verify this thing if that's not correct then we send a wrong password bad request back but after that we're creating the Json web token and now here's the place to also create a refresh token and set the refresh token in a cookie and this will be an HTTP only cookie why is that well with that it is inaccessible with JavaScript so it is only used to send this to the server and the server then is doing its magic with that so for that we need two methods and I will Implement them in a sec first the refresh token here we will use a method called generate refresh token all right and then another one to set the refresh token in the cookie and this then will be the refresh token here now the methods first one private returning a refresh token called generate refresh token like that error is gone nice and this thing now looks like that so this is a new refresh token Yep this thing is required course and this is interesting formatting and now the only fancy stuff we hear do convert to base 64 string I told you I want to have a random character string here and then we choose or use the random number generator using system security cryptography and here now get bytes and maybe 64. all right after that now the formatting Works nice we say expires in date time now and add days for instance seven so this thing then is valid for a week and and here's something expired expires all right now this should work okay create it by default this daytime now so I think we don't need that and in the end we just return the new refresh token all right and let me let me just stop the app of course I hit save a bit too early because we haven't implemented the set refresh token method but this is what we're going to do next so private voids set refresh token refresh token new refresh token right so we're sending or giving this as an argument to this method first thing now cookie options I told you that I want to set HTTP only to true so let's do that here so the cookie options are done like that just new cookie options simple right and here we say HTTP only is true and again expires set to end Days 7 or what you can also do of course we say new refresh token expires that's nice and here now we say response cookies append refresh token and then new refresh token token and our cookie options with that we have our cookie and additionally we also want to set the data here to the user object so our refresh token is the new refresh token token then token create it created and the last thing user token expires this new refresh token expires and now down here in the Json web token I said that this is no valid for one day again usually now you could you could set this to an hour for instance so for instance at I was only one so maybe this is then more realistic according to GPT at least all right so we've got now the set refresh token method this is done we've got generate refresh token and this is what we're now doing when we're logging in and maybe we can test that already so let's start the app here here we are so now let's say we want to register with string string and execute so we've got this new user and now we log in with string string as well we get the Json web token and when we also open the the console and now we can have a look in the application tab not the local storage in the cookies now we've got a refresh token isn't that nice and this is really this random string I was talking about isn't that great so this is what we get here and now when we send a request so we set our well we actually don't have to do that because with the or in the network tab we can see that we can run this we hit execute and we get the 401 back but still in the headers we now see our refresh token all right so that's already nice but still there's one more thing we have to do and this is well getting a new refresh token so refreshing our refresh token all right for that we need another endpoint so let's just implement it down here maybe and this is a post method HTTP posts URL maybe refresh token again public async task action results refresh token and actually we are returning a string here so we could of course also enter that here so now the thing is with that method we are not only refreshing our refresh token we are also returning a new Json web token so that only this thing now or this is the new one that is a valid all right and the new refresh token is also the only refresh token that is valid because you would check if this thing matches then with the refresh token that is stored in or stored for the current authenticated user or the user that tries to to do something with this with this API all right so now again VAR refresh token is requests cookies and then refresh token and with that token we first want to check if this is actually correct right so if user refresh token does not equal the the given refresh token here and then we return something like unauthorized and embedded refresh token Maybe and additionally we check if this thing is still valid so user refresh token almost it's actually token expires so token expires is less than smaller than date time now and in that case we also return unauthorized and then token expired and that you of course have to decide for yourself because could be a valid request it is the real user with the validation web token or the valid refresh token but it just took the user too long to log back into your application how dare this user why is he or she waiting a week to log in to your app so now here we say create token and if that would be the case of course the user is logged out and the user would have to log in again I think it's not that bad we get our new refresh token again with generate refresh token and again we set refresh token new refresh token and we return okay token alright and this is actually no asynchronous method that's correct but if we would use an Entity framework here for instance then this would make sense but I don't care here now so let's just restart the application I think you get the idea we're back here now we have a new endpoint what is happening when I just do it like that I get invalid refresh token isn't that interesting right so of course no user here because we restarted the API so let's now use another user Joel please with Ellie it's still a really really big fan of maybe you guessed it the last of us and now we log in try it out Joel and Ellie we hit execute this is now our beloved Json web token great so now what can we do well we can check that authorize close do we get our name yep beautiful this works and now here where is it refresh token again we hit execute and we get a new Json web token well now this token is valid for a complete no for an hour so maybe I would have to wait for an hour don't want to do that but we can do something else actually because here now we see or maybe we can have a look here in the application tab again we see this value right so now what we can do is to check if let's have a look here again this thing is invalid or you want to already use an invalid refresh token we just remove the queue here was it a queue I hope so execute invalid refresh token now let's put this back execute Yep this is now our Json web token again this works but now to test if this thing is invalid and you see here this thing changed right so we really get a new refresh token and now let me just change the date there we are in our seven days or just a bit more let's change it to this state here and you try to execute it again token expired all right so this works and this is how you implement refresh tokens if you haven't watched the complete series yet make sure to click the video on the screen to watch it right now
Info
Channel: Patrick God
Views: 7,972
Rating: undefined out of 5
Keywords:
Id: _F2hB4cWg-M
Channel Id: undefined
Length: 18min 24sec (1104 seconds)
Published: Tue Apr 04 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.