Easy & Secure: Add Refresh token in .NET (C#) WebAPI with JWT Authentication

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what is a refresh token why do we need it how does it make our system secure how to implement it find out in today's video hello and welcome to code with star i'm sar how are you doing today today i want to respond to a question from dev4g about the role change in the authentication verbal king it is from my previous video talking about policy based authorization it is a very good question thank you dev4g for bringing it up basically the scenario is an access token got issued at the same time the role of the user has changed so how does the system deal with it well this is a challenging scenario but also very practical and i believe there's mature technology being there to address it we just need to find it out and i think that piece is a refresh token so let's talk about it here i'm going to use an analogy to explain what is a refresh token and why is it important let's meet sam when sam was born he was given a birth certificate imagine that as username and password that proves his identity time flies he's 18 now it's time for him to get a drive license so he goes to an authority like the department of license show them the birth certificate and of course take the test let's ignore the details under the authority give him back the drive license and that is the access token that is approved of the identity as well as a role of a driver now sami is going to do something with it let's say rent a truck of course why not so he brings his license to a car rental the rental agent checks the license verify the signature making sure nothing is tempered and they issued the vehicle well think about what happened so far you need to have a driver drill before you could get in vehicle which is the protected resource right okay that all makes sense but unfortunately sam has not been a good driver the authority decide to revoke the role of driver from the identity exam what need to happen and that is the scenario that we are talking about today revoking a draw wait are we not going to talk about refresh token today we're going to stay with me a little bit longer it's going to work zero time but if you really only care about the implementation jump ahead use the chapters okay the dol decided to revoke the drive license from sam there's one major problem when the driver's license is presented how does the agent know that it hadn't been revoked one way it wanted to always check with the authority of course that's going to put a lot of pressure on the authorities mapping that to the digital world incorporating the identity server or dedicated identity service to handle that we're looking for something more efficient here's the idea how about put the expiration date on a driver's license once sam's driver license is expired he has to go to the authority again presenting his birth certificate aka username password and get a new driver license and that is the chance for the dol to say okay sam we're going to issue an id card but you cannot use that as a driver's license and that's the drivers role got revoked of course there's a problem for that the driver's license doesn't expire for years and a lot of damage could be done during the period but in the digital world this problem is relatively easy to solve how about the excess token expired in one hour okay now how about 30 minutes fine 10 minutes we can do that how about five five minutes we could go even shorter than that but again there is a problem every time the dlls issue a new license to sam or your service issue an access token to the user they need to prove their identity by using a birth certificate or username password oh that is not a good experience you don't want the user to login again and again here's how to address that problem think about sam went to dll for the first time well birth certificate right okay say everything went well the dll handed out the license in addition they created a ping on his file and they give the same ping to sam telling him next time if you need to refresh your drive license give us your own license and the pin as far as the ping match the record on sam's file they're going to issue the new license no birth certificate needed and when sam gets the new license he always get a new ping well you know the story sam got into accidents the author of the admin steps in scrap out of the pin the old license got expired soon and sam's pin doesn't match the record any further and since sam cannot get his license renewed he then lost his truck well it is a sad story but the point is the ping is a refreshed token it allows us to issue short-term access token which is safer it allows the user to avoid logging again and again and at the same time the administrator has a way to require the reader to login again by remove the refresh token from the user's file based on some events like for example suspicious activities of an access token or a low change of a specific user i wish this couple minutes worth it so that not only you know what is a refresh token but also why is it there and when is it useful well finally it is time for us to look into the implementations let's keep building the jwp auth in web api project well on the roles branch for the new to the channel i'm going to go over this project briefly so that we all have some context but if you find it difficult to understand what i'm talking i highly recommend you to go back to the existing videos to watch the basics let's begin with startup here we have authentication setup to use jwt and we have three controllers among them token controllers used for authentication we post on the route of token with the proper credential like the username and password and we get back the access token that is a driver license a small detail is that the current role is hardcoded to admin and you are supposed to get it from somewhere like a database right also related to today's topic there's expiration on the token already it's five minutes the other two controllers provide protect resources one for the user and another for the admin now let's build up the refresh token the very first thing we want to do is put expiration onto the xs token you're going to figure out your number there for the demo purpose i'm going to make it really really short and i'm thinking about 30 seconds now if you debug immediately you're going to see the token valid for more than 30 seconds so pay attention this is going to save you time you come to the startup set up the clock school to timespan.0 the default value is 5 minutes and that's too long a wiggly room for the expiration check and our scenario you also want to make sure there is no custom lifetime validator no let's run our first test here i prepared my username password make a post on the token endpoint here we go this is the access token let me copy it and i'm going to use that to get admin resource well this is proof code and we all know it's going to work right the only change we made so far is on the expiration so the token will expired after 30 seconds so i'll just burn a couple of seconds by talking to you and now let's try it again okay for one unauthorized the token is not accepted by the system any further because it expired great well as a client at this moment to access the resource again we need another access token we could go to the login page again supply the username password or we could use a refresh token except that we don't have one so next we're going to write code to create a refresh token let's see the code the current access token is returned as an anonymous class we're going to add more properties so let's make it a class i'll call it authentication result and it will have a property for access token a property for refresh token and another property for expiry now the expiry is not 100 needed because the same information is there in the access token but it makes the client easier that it doesn't need to decode the jwt token by itself coming back to the token controller i'm going to create a concurrent dictionary to hold the refresh token for any given user now this is very very important a refresh token belongs to a given user in real project you actually don't need this dictionary what you would do is to put the refresh token along with your user record in other words if the user information is in the database put their refresh token in the database make it one-to-one or one-to-many relationship that is important because when you revoke your level could refresh tokens for a given user now let's write a method to generate the refresh token for a valid user the token could be any type it needs to be serializable and obviously it cannot be guessable i am using a guide here because it is simple but if you search online there are sophisticated ways to generate refresh tokens the method by itself need to reach two goals actually one is create a new token every time it is called and the new value need to be persistent to a place where you have your user records the code that i'm writing here only works for one session and it doesn't scale at all but it makes the point now let's see how are we going to use it let's update this get access token method to return authentication result so it will include access token refresh token and the expiry on line 44 the user credential is validated so we don't need to worry about the validation let's pull out the expiry because we're going to return it later now we update the return type to authentication result here we call the new method generate refresh token again the username has already been verified we're going to use it directly into the expiry now let's update the color let's draw the code and we expect to see the refresh token on the side of the access token being returned it looks great to me now that we have the refresh token let's take a look at how to use it let's create a new route on the controller i'm going to name it get refresh token it will take an authentication readout and that's going to be the expired access token along with the refresh token i'm going to give it a router refresh and use the verbal post this method is going to be very similar to get token the difference is that a get token verifies user by username and password here we're going to process the existing token and making sure the refresh token is in effect so let's start by overload the get access token method let me copy the whole method and i'll change the parameter from logging contract to authentication result of course the is valid method need to be rewritten as well because that is a core for validation the rest of the code generates the access token it is very possible this could be abstract out and refactored to be reused but for now let's keep the duplication it looks like what is missing is the only username we know the username is there on the access token so we're going to extract it from there so this valid method is going to return it let's write it it's valid takes in authentication result and return the result of boolean at the same time output the username now the username is on the claims principle of the expire the access token i am going to show you how to write the method to get the claims principle from the token but for now let's move on assuming the principle is correctly extracted then we need to verify the principle is not null if it didn't let's find out the username on it and the username should not be null or empty now we have the username let's extract the given refresh token it happens to be a grid here but we could do other validations if it's a different type as well let's use the username to extract the current refresh token and then we need to make sure those two token matches each other and if it passes all these tests we're going to say yes this is the valid now let's get back to get principle from expired token let me start by generating the method we want to verify the access token even though it is expired everything else should still be fine the first step is for us to have a token validation parameters we have had one in the startup so we're going to copy it from there the difference is we don't care about the clock skill here and we don't want to verify the lifetime so i'm going to delete the clock school at the same time i'm going to set validate lifetime to false next i'm going to give this the token validation parameter to a token handler and use the token handler to validate the access token this will return the principle that we want as a side effect it also return the security token and since it is a jwt security token we can do some additional check on it once done i'm going to return the principle let me format it a little bit and then here we go all right i think we have all the parts that we wanted i just need to update the color a little bit to wire everything up let's run the code and try out the new route i'm going to firstly post a token using username and password as usual then i'm going to use the access token to get this admin resource again i'm then going to wait for a bit just to making sure that this excess token expired now instead of going back to the token endpoint i go to the refresh route pasting the authentication result this is the one with the expired access token but a good refresh token and i used that to get a new access token into refresh token and then i'm going to go back to the admin resource just to verify that the newly get access token works and it does now if you have a front-end client for example a javascript client once you have the authentication result before issuing any request to the protected resource you check the expiration first if it has already expired hit the refresh endpoint to get a new access token before issuing the call and that doesn't require any user interaction at all if you reach this part of the video i want to thank you for your time first now let's think about one interesting question if a hacker gets your short-lived access token he properly gets your refresh token at the same time and if you could use your refresh token to get a new access token so does the hacker then what are we doing this question got me for a while until i realized the biggest difference in between those two tokens an access token once issued it is very difficult to revoke you could consider switch out the private key then all the signatures become invalid and that impacts every user for your system but for refresh token is relatively easy to revoke now a hacker gets your access token he could use it for 30 seconds and the refresh token got revoked and the hacker cannot get another access token that's how it keeps the system secure to make it even more secure you can put expiration on the refresh token as well coming next let's look into how to quickly implement a dribble kind point now when we revoke a refresh token we usually revoke it on a specific user so i'm going to use the username as a parameter what it does here is going to remove it from the dictionary and then in the real project it could be update a record in the database so that to set the refresh token to know no matter what we do the goal is so that the refresh token on the record will not match the one in the user's hand what a sabotage action oh and if you are writing an endpoint like this don't forget to protect it that only your administrator can access it now let's verify it works at the very beginning the user need to go to post token to get an access token for the first time this is the username password scenario once that succeeded he or she then can go to the refresh endpoint to refresh the token now imagine the administrator don't want the refresh token to work any further so we step in and revoke it again this operation usually is per user after that it's done let's come back and try to refresh the token again voila no valid refresh token in system of course handle the exception you don't want to spell out that much information to the intruder okay we talked about what is a refresh token why it's useful and how to implement one and how does revoke work i hope you enjoyed the video if you find it helpful give me a thumb up let your friends know subscribe for more and keep coding keep improving i'll see you in the next one until then take care
Info
Channel: Code with Saar
Views: 5,578
Rating: undefined out of 5
Keywords: webapi refresh token, .net refresh token, refresh token, jwt, jwt token, jwt authentication, role authentication, role change, 2022, .NET 6 Authentication, .NET 6 Authorization, .NET 6 WebAPI authentication, C# JWT, ASP.NET Core Authentication, ASP.NET Core Revoke, Role revoke, Token revoke, Revoke token, Short lived token, access token
Id: TWBXiCS0RYM
Channel Id: undefined
Length: 25min 51sec (1551 seconds)
Published: Tue May 31 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.