Refresh Tokens with a .NET 6 Web API 🚀

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends welcome back to the channel thanks for dropping by my name is patrick god and in this tutorial now we're covering something that you wanted to see for a long time and lots of you guys wanted to see that we're talking about refresh tokens and we are also implementing them of course and i have to tell you i am really really happy and very proud that this specific video here is sponsored by skillshare i'm pretty sure you know what skillshare is but in case you don't now skillshare is an online learning community with thousands and thousands of inspiring classes for anyone who loves learning and wants to explore their creativity and learning new skills like programming of course dotnet 6 blazer c-sharp or programming in general whatever it is skillshare is the perfect place to invest in yourself and your personal growth now if you have a specific skill you're trying to learn like authentication for instance or authorization.net 6. skillshare is the perfect place to start from not only programming but also photography illustration graphic design freelancing productivity that's what i really like you can find classes that will match your goals and interests and i can already tell you now that of course i also will create courses on skillshare for instance this authentication and authorization jumpstart coursewith.net 6. and there we will also have a look at refresh tokens starting with json web tokens of course and then also covering roles so not only authentication but also authorization and then also implementing refresh tokens and we will go a bit deeper there we will also use a database where we store the users and the tokens the refresh tokens not the json web tokens the refresh tokens and then fiddle around with that and what i really really love about skillshare is that these classes most of these classes are only one to two hours long maybe three sometimes but i love that you really get jump start courses like mine and maybe also future courses i create so you get lots and lots of information in just a few hours or even minutes so maybe you want to have a look i personally love also the courses of marcus brownlee regarding youtube because i'm doing this here and also the productivity classes of ali abdal or thomas frank so make sure to join this great community and use my code patrick god that's me so either just use this coupon code or head down to the video description and then use this link to get one month of skillshare for free so essentially you can get all the courses i talked about and my courses on skillshare for free so don't miss this opportunity i can wait just hit pause i'm taking a zip of my coffee [Music] the code yet okay great so now i would say after you join skillshare enjoy this tutorial here on my channel all right real quick i rarely do this in my tutorials but please if you want to do this hands-on and code that stuff with me then please check out the github repository in the video description because this is kinda part kind of a part three of an authentication and authorization series on my youtube channel we already covered the json web token stuff then we implemented the roles and now i'm going to show you how to use refresh tokens in a custom authentication authorization implementation with net 6 and web api so this is the github repository jwt web api tutorial again here we will see something about logging in a user registering a user and creating a json web token and also adding roles to that token but now in this little tutorial we will add refresh tokens and make use of them now again for the recap let me open visual studio this is how the the code then looks like you will see here that we've got no database whatsoever what we do here pretty simple actually we just store a static user here in the auth controller and do something with that user right so when we register the user we will set the name and the password hash and solved and so on but this is part of the first tutorial so please have a look there i think we don't need this so i can remove that and save it and it should be rebuilt and then let's have a quick look what the application is actually all about so when you start this thing we can use swagger ui here this is pretty neat to well test our application and what you see here is we can register a user and this user again will then just be set the static user will be set with the username and the password hash and salt of course you can change that or you just leave it at string string pretty creative i know but let's just execute this and now the user is registered of course in the real world you would not return the password hash and the salt or the username well maybe the username but of course not the password hash and so but for learning purposes i think this is totally fine and now what we can do is we can log in with the same credentials so string string and what we see here now is the actual json web token let's copy this thing already because now the thing is in essence this is now the responsibility of the front end so whatever you want to do with this token is up to you or the front end do you want to store this in the local storage do you want to store this token in the session storage or do you just want to store this not at all or just memory right so when you'd want to do this just use the json web token in memory and well enable the user then to to still use the application the next day without logging in again then you might want to combine this with a refresh token and because with the help of a refresh token you can get a new json web token but you will see how this works in a minute let's just copy this thing now and this is now our secured endpoint here this auth thing which is just returning the username when we try this out and hit execute we see an unauthorized code here the 401 this is what we get from the from the here's the request method in the status code now this is what's coming back all right from the service and now we can set this token here the bearer token authorized close execute again and we see the username string isn't that nice okay so this is just a quick recap of the current application and now let's implement the refresh tokens so we go back to visual studio and what i can already say is that there's no fancy algorithm stuff or anything like you have seen this with the json web token right so when we generate this here you see the claims you see the signing credentials the security algorithm and so on not necessary here a refresh token in essence can be anything you want so in our case this will just be a series of some characters and the very first thing we will do is add a new model so right click our project add a new class and call this simply refresh token and now again we are not using a database here we do this in the skillshare course though so please have a look at the video description and grab your free trial of skillshare there you will be able to enjoy this complete course then but for now let's just give this thing three properties first the actual token which by default is string empty all right and then two more things but again this is really up to you there's no well how can i say this defined implementation there's not one best implementation for refresh token i would say there are several ways to do this so we here implement a really simple way because this model here will be used to also store these information uh with the user right so we've got the token string we've got a date when this thing is created daytime now and we've got an expires date and this is important with that we can say okay now let's say the refresh token is valid for seven days and you come back on day eight and then the user has to log in again but within a week the user could actually get a new json web token just with the help of the refresh token right so this is what we do and if you want to use well let's say more comprehensive implementation then you would also give this refresh token an id and store all the refresh tokens of a particular user in a database and then you can also revoke them you can say okay this refresh token is old this is not valid anymore but it's related to this specific user so if someone is trying to use this refresh token and there's actually a newer refresh token but somebody used an older refresh token then maybe something fishy is going on here okay so this is what you can do with a refresh token in a sense nonetheless we've got our refresh token model and now let's go to our user model and add this thing here as well so we've got another string call this refresh token string mp maybe again so string empty and then also the dates date time that created and also date time uh token token expires and actually i wanted to call this token created token created and token expires all right so this is what we do again this user here just a static user right here not in the database nothing like that we so we don't need a migration or anything we just do it here real quick and dirty okay now what we want to do next is when the user is logging in then we not only create a json web token here all right so we've got our login method we test if the username is correct and the password is correct and then if so we create a json web token but additionally we also want to create a refresh token so let's write this down here and we will add the methods for that in a minute so first this is the refresh token let's call this method then generate refresh token and also what you want to do is set refresh token and with this method then we will set our http only cookie why http only well that way no javascript is able to get the value on in the browser so this is hdb only we can just use it with our requests so that's that and now down here let's create our generate refresh token method so private refresh token and then generate refresh token all right and in here now we say refresh token is a new refresh token and we already set some values and this is the only fancy stuff here we say convert to base64 string and then random number generator get bytes and let's say this is 64. all right so this is then our token this thing expires in let's say date time now at days seven and it is created where we did this already in the model but still date time now all right and now we return our refresh token okay so this is how we generate the actual token and now we want to set the cookie so we add another method here private voids set refresh token with the new refresh token all right and here now we say var cookie options so this will be our cookie new cookie options and here we say very important http only is true and expires is not daytime now it is a new refresh token expires all right and then we say response cookies so this is pretty easy with dotnet append and this will be the value of the cookie and here we say new refresh token token and also add the cookie options and that's how you add a cookie to your response and now also we set the the same stuff for the user so our token is the new refresh token token user token created is new refresh token token created created all right and user token expires is this value here okay and with that we can actually already test that don't know where the error is drain refresh token generate oh get refresh token of course it's generate refresh token save this again and start the app again and then we have a look all right there we are okay so nothing has been changed here but when we now say we register this user with string string [Music] and now we log this user in okay hit execute and now let's see response headers set cookie refresh token see that http only so this is now the refresh token and when we go to the application section here we also see our refresh token here isn't that great so this is how we already define the refresh token and this now is automatically sent with another request so when we now say let's uh try this endpoint here we hit execute of course we get a 401 back but what we see now here with the request headers cookie refresh token so this is already sent with this request no matter if we send an authentication header with this or not the cookie is sent nonetheless and this is what we will use next we will try to get this refresh token and check if um this thing is valid and then we generate a new refresh token and refresh it so many refreshing tokens here today so let's go back to visual studio and so we've got our set refresh token generate refresh token and now we need another endpoint all right so let's do this here this is now an http post in essence could actually be also a get no let's let's use a post and we call this refresh token and this is a public async task i action results actually let me double check yeah we will use the string again because why why did i check this i want in essence do the same thing we did here i only want to return the string here which will then be the new json web token and the refresh token the new refresh token will again be sent with the cookie another option would be to use and let's say an authenticate response dto so an object where we send then the json web token combined in one package with the refresh token and also the created and the expires values of this refresh token this then can be stored in the front end for instance so the front end can do a bit more with that because the crucial thing here is and that's the question the question i asked myself when i learned about refresh tokens when do you decide to call this endpoint right so when when should this happen and this is totally the responsibility again off the front end so when the front end says hey um i see my json web token is expiring in a couple of minutes or in a couple of seconds or something then i automatically call this or another thing i already saw is that you call this um this end point in an interval so you say every five minutes or so i want to get a new refresh token and so you can do this as well with this endpoint then so we just call this refresh token because we want to refresh our refresh token should get a refreshing drink and now first what you want to do is we want to get our our cookie and of course we cannot use the interface here and this is returning nothing but it will in a minute so first we access the cookie and the refresh token so bar refresh token the one that was sent with this request now is simply request cookies and then in brackets refresh token isn't that great and now we check is this thing valid so what you can do when you use a database you will have a look for the user that currently has this refresh token but in our case we only have one user so what we do is user refresh token if this thing is not equal to this refresh token now then we just no semicolon what we do then is we return an unauthorized with a text like invalids refresh token and also what if this thing already expired then we say user token expires smaller than date time now and in this case we again return unauthorized but maybe with another message here we say token expired all right otherwise if everything is okay then we say we generate a new json web token with create token okay for this user here and then we say bar new refresh token is generate refresh token and then again we set this new refresh token new refresh token and again we return ok token all right quick recap we get the refresh token from the cookie we check if everything is okay with that refresh token if so we generate a new jwt a new json web token and also a new refresh token and we return the json web token and set the new refresh token to the cookie and now we restart our application and test this and then you see that in 20 to 30 minutes you already have implemented your refresh token functionality in the backend not in the front end but in the backend and a really simple one so maybe you would want to invest some more minutes to use a database here so we've got our new endpoint here refresh token right what happens if we do this here let's try this out it executes well invalid refresh token okay this is great this is absolutely correct because we have a wrong refresh token here because we reloaded restarted the complete application so let's try the that again we register a new user try this out it executes then we log this user in all right and here we get our json web token and we also get our refresh token and now let's have a look and focus on the refresh token so this is the value here c5bg and so on and now what we can do is we can try this endpoint here again we hit execute we get a new json web token isn't that nice and you saw it here already we refreshed our token our refresh token so we hit execute again and again and again and you always get a new refresh token and now let's say again we manipulate this so we removed something here it executed it says invalid refresh token when i add the one here back then i can see i get a new json web token and now let's change the date give me a sec just a time there it is so we changed that we've got may the second and now let's say we've got the 10th maybe change this and try that again it executes token expired isn't that great and this my friends is how you implement a really really really simple way where you can use a refresh token make sure to check out the video description for the github repository of course i will push this in a minute and also don't forget to join skillshare and grab your free trial that's it guys just maybe half an hour and you are using refresh tokens with your whole authentication implementation pretty easy right don't forget to grab my code patrick god that's me to join the skillshare community and then you can get the complete course where we go from creating users or registering users creating json web tokens and also refresh tokens adding roles and so on and you can do all that for free so isn't that great grab the code or check out the link in the video description and additionally if you like this video then please i would really love it if you click the like button and maybe even subscribe to my channel currently i try to upload a video every single week on tuesdays don't forget the bell icon to get a notification for new videos don't forget to also consider joining my newsletter that would be really really nice that way you get these youtube videos here earlier in your inbox and a couple more stuff promise won't spam you at max i send an email once a week maybe rather less but still you will get an email by me and the last thing my coffee unfortunately is already empty again but thank you so much to all my supporters getting me a coffee or tea or whatever it is thank you so much for supporting me this is the way i am able to create all these videos and if you're still with me thank you so much and maybe here are some other videos you are interested in if so just click on the thumbnail and watch other.net and blazer stuff and maybe also some other stuff you're interested in we'd love to see you here on my channel again thank you so much for watching thank you so much for your time and i hope i see you next time take care
Info
Channel: Patrick God
Views: 38,838
Rating: undefined out of 5
Keywords:
Id: HGIdAn2h8BA
Channel Id: undefined
Length: 25min 41sec (1541 seconds)
Published: Tue May 10 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.