Spring Boot Security - JWT Refresh Token Explained In Details | JavaTechie

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to Java techy in this tutorial we'll demonstrate how to implement repress token mechanism in a springboard application which is secured with JWT okay all right before I continue further I am assuming that you guys have complete understanding about how to implement security using Json web token or JWT if not then I would strongly suggest you to check out my Spring Security with jw2 video which I already uploaded springboot 3.0 Spring Security 6 JWT authentication and authorization I'll share this link for your reference take a look then come back to this current course otherwise it will be difficult for you to understand okay cool so let's start understanding why we need refresh token or what is the importance of using this refresh token mechanism so to make this simple let me walk you through the flow of JWT security you can see here we have two components the client which is the user who is accessing the application and the server is the application itself where you have implemented JWT security so first step client needs to send one time credential to login into the system once server authenticate the credential it will generate the jwd token and send it back to the client again now going forward client or user can use the same token for any future interaction this is the typical JWT security workflow right what is the problem here generally in an Enterprise application ensuring that the security of the application is preserved there is an expiration time set for the generated token after which the access token is not in any of the use so assume we have set the token expert limit as a 10 minute and let's say the user is trying to access the same token after one hour which is already expired then definitely he will end up with 403 Forbidden error now what user will do he will follow the above three steps to get the new access token which is really annoying for user isn't it because we can't force to re-authenticate every time when their access token expires this will give a bad impression to the end user and also there could be a possibility that people will be stopped using my application itself then how can you overcome it that is why this refresh token mechanism was introduced which will help to improve the security and user experience of our application insert you can say it will simply extend the X pair limit of your token so whatever the token you will get initially it will just extend the expiration limit of that particular token so what basically we need to do we'll write an API in server application where it will take old token as a input or old token ID as a input and it will return a new one with extending the token expand limit okay so going forward user can pass the same token to access all the API now when the token expects then the user can happily call the refresh token API to renew it rather than reauthenticate again and again I hope this gives you a clear picture about why we need a refresh token mechanism okay so without any further delay let's quickly demonstrate this particular scenario in action so let's get started foreign [Music] so before we implement the refresh token mechanism first let's verify the JWT security flow we are basically going to perform step one two one three okay so let's go to the IntelliJ IDEA we are going to use the same code which I already explained as part of my Spring Security JWT video you can find the source code Link in video description okay now what basically I'm going to do I will just start the application you can see here it started on port 8080 now just go to the postman and basically we need to add a user to the DV then based on that username and password we need to login to get the JWT token then using that token we are going to access the other API okay these are the three steps we are going to perform that is the default security flow in JWT so just go to the postman this is the user I am going to add okay now the endpoint you can see here sign up click on send user added to the DV if you go and check in your DV if I will refresh this you can find the user here okay that's fine now by taking this username and password I need to authenticate or I need to login to get the JWT token so simply let me hit this endpoint I got the JWT token Now using this particular token I can able to access the end point so first let me remove the token I am not giving any token and I'm sending the request I am getting 4 not 3 which is forbidden error you are not authorized to access this particular endpoint without any token now let's give the token send the request we are able to see all the response okay but if you verify this token go to the jwt.io and paste your token if you will see the expired time will be 1553 okay it's just for three minute if you check in the code we have just specified the token will be expired after three minute when it release or when it created okay so now what we can do we'll pause for one or two minute and we'll try to access the same endpoint to get all the product and then we'll verify the behavior okay now the current timestamp is 354. and it already expired on 353 okay so let's try accessing the same API to get all the products using the same token which is already expired okay now send the request what we are getting four not three forbidden if you will see in our console there is error let me Zoom this for you JWT expired at this time current time is this a difference of this time millisecond allowed clock zero millisecond okay so JWT itself is telling us hey the token which you are trying it's already expired now what you can do very simple step right we can simply go to the login and will regenerate the token and you can copy the token go to the API change the token expiration or change the barrier token here which will having some extent of your expiration limit send the request you are getting the response now if we'll verify this new token it will be experiment 358 okay so again if user will try to access the same token after some time interval or after it expired then again you need to go with the step one two one three to overcome that we must need to implement the refresh token rather than forcing user to re-authenticate again and again we can tell them hey you can simply call the API to extend your token or you will get a refresh token ID by taking that ID you can get a new token and going forward you can use it okay that is your something the refresh token we want to implement so we understand what is the drawback without refresh token now we understand what is the importance of this refresh token so now to generate a refresh token and to compare it with the old token we must need to store it somewhere right so we can store it in our DV then we can compare it with the old one and we can validate the expect time if required we can return a refresh token so for that we must need to create a new entity to store the old token ID or token with the expired time so go to the entity I'll simply create a class now here you can Define couple of field like ID token and expired date so let me Define them so once you define these three field also you need to map this particular token to a specific user okay so if you remember we if you will go to the entity we have defined the user info entity right so you must need to map that specific token to the user object so that you can easily identify this token is belongs to which user so how we can do that just add this user info and you must need to map them using one to one and we need to Define join column and next you just need to Simply Define the name of your field and then who is the reference column the reference column will be your user ID okay so this particular token must need to map to a user so that we can easily identify it now we must need to Define The annotation this will be my ID and I want it to be Auto generated Define the strategy identity that's it you need to Define this at the rate entity and you can also Define the data next simply since you created The Entity you must need to create the repository right go to the Repository refresh token Repository now this is the interface you must need to extend it from foreign Define the target which is your refresh token and Define the data type of your primary key which is integer all good we have created The Entity we have created the repository now the next step if you understand it correctly we need to write a API to create a refresh token so for that what I will do I will simply create a service class next just annotate this at the red service and inject the repository here inject using Auto add similarly you must need to inject the user repository to get the user information fine now let's create a method public will create a refresh token and return it to me this refresh token method will take the input as a username because while giving the JWT token itself I must need to give the refresh token okay so that going forward if token will be X Pair by passing this token value he can get a new access token so that is the reason I must need to pass the username based on this username I will get the user info from the repo next just build the refresh token object user info you will get the user info from this user info F4 right that is the reason we have injected it dot find by username and pass the username it will get the user object for you next what is the field we have expired date and token token will be nothing you can set something new uid value so let me set that uid which will be some random string okay dot random uid Dot tostring next will be the expiration time right expect date you can use instant dot now then plus millisecond like this and I am trying to set it for 10 minutes so that is the reason I have given 6 lakh millisecond okay next simply build the object this particular object we have to save to our DV where this is crying okay this expect the optional so we need to do the get curve now get the reference simply use the refresh token Repository called the same method and give this particular object okay so we have written the method to create the refresh token by taking the username now if You observe when we did the login right we got the jwd token now what we want to do now once user will try to login along with the JWT access token we also want to give the token value which is nothing the new random uid string which you are storing into the DV so we also need to do that changes here okay so for that from where I can do the changes I have created the method just copy the method and if you go to the controller this is the place where we are just generating the token and return it back to the response so while returning the jwd token we also need to send the token refresh token okay so what I can do simply I can call the method from here so first I need to inject the service here inject using Auto add next we can use this service go to the method here here you can call the refresh token service Dot create refresh token we can pass the username from auth request dot get username okay simply get the value so I send it to the variable now it's straightforward right we have the refresh token value with us we have the JWT access token value ethos we just want to combine both of them and we want to return it so rather than return the string what I'll do I will create a JWT response dto class here I will Define two fields okay so access token is nothing here JWT token this refresh token or you can name it token okay this token is just a euid based on this uid you can ask to the JWT to give a refresh token so for that we are going to write and separate API okay so Define all the long box specific annotation fine then use this specific class as a return type instead of string now what we want to return here just write jwdresponse dot Builder I want to set the access token which is nothing here this line of code which is already there okay access token is nothing your JWT token the real one first which one is generated then next you need to set the token is nothing the unique ID of your refresh token how you can get that value let me remove this piece of code this you can get it from this object refresh token dot get token value okay now you just need to build it that's it we want to return it fine now we'll verify it quickly how the response looks like now after adding the refresh token as part of the response quickly restart it okay before I restart I need to delete the DV because we have mapped the mapping between two entity so let me stop it now let me restart it so you can see here it started on 8080 go to the postman first again since we deleted the DV we need to add a new user let me add the same user user added to the system go to the login I'll give the same username and password send the request can you see here we are getting the access token that is what the jwd token by giving this token you can access any endpoint let me show you that that is what the default view right we are getting the response then what is this other field this is the token ID if your token will be this access token will be expired you need to call the refresh token API by giving the specific ID okay you keep a reference of it or else if you go and check your DV Let me refresh it there will be two table right let me create a new SQL I'll check this we have this user and it will verify the refresh token we have this token ID same and this specific token map to the user id1 user id1 is going to this guy person okay that is the reason we have mapped the user ID to the Token now going forward you must need to pass the valid token to refresh it okay I will show you that by writing a separate endpoint so let's go to the IntelliJ and we'll write the separate endpoint here I'll write a method public will again return the anything you can return let me return the response entity or you can return the JWT response itself okay refresh token is a method name and this should be the post mapping I'll Define the URL as refresh token okay and what it will take as input it will take as input this token which is a string how can I pass this particular field I cannot pass as part of the header which will be security breach for me or I cannot pass it as part of the URL correct I must need to pass this specific field as part of the request body so for that what I can do I'll create a separate dto class and name it refresh token and I will just Define the field here again you can Define all the long box specific annotation okay go to the controller class pass the value I mean the request and this must need to be annotated at the rate request body because we are giving the object fine now we have the token this particular request contains the token field Now by extracting the token first I need to verify whether the token what I am giving is correct or not or the token which I am giving is there in my DV or not so for that what I can do in my refresh token service I'll write the logic to verify in the DV by taking this token ID are you able to get the token object from the DV or not so that is a simple get call from the DV right so I'll write a method here private get the optional of refresh token next what you can do you can write the method name find by token or something like that pass the token here simply call the return you have the repo with you right refresh token repository Dot find by and check the field what you have defined in your entity is token right so you can Define the method name like this find by is the prefix and based on which field you want to search as it and give the token value now it will force you to create the method in your repo create this method that's it okay now also you need to write a logic to verify the expiration limit of the token on token is valid or not okay so for that what you can do you can write another method so make sure this should be public not private because we are going to call this method from our controller class okay write another method to verify the expiration of the token public okay which will again return the refresh token after verify it will take the object itself refresh token very simple okay now how you can verify that very simple just get the token from the request token dot get its expert date if the token dot gets get expired there compare this value with instant now okay with the current time if it is greater than sorry Less Than Zero then this token is already expired no use of it simply what you can do you can throw the exception through new runtime exception token this particular token was expired please make a new sign in request and also since this token is already expired no use of keeping this information right so what you can do simply we can delete it from DV agile refresh token repository dot delete the refresh token okay pass the token object otherwise simply return the token if all good there is no error return the token which is valid fine we have written two method to get the token from DV to verify whether the realities exist in our DV or not and we have written another method to verify the expiration limit of that token that's it now simply call these two method from our endpoint so here I'll just use refresh token service find the token first give the input refresh token request dot get token okay which will return the optional now just check the X pair limit of that token so simply I can call though like method reference okay verify expiration once it is verified then again just get the user details from the refresh token object dot user very simple so you can call refresh token where is the user yeah this guy now you have user information with you simply you can play with this particular user object to regenerate the token okay you can call JWT service Dot generate token and you have the refresh token value with you okay I mean the ID with you just map it so rather than return the response entity I will just return the JWT response so that we can build it dot Builder okay set the access token which we just generate through the JWT service generate token and next you need to set the what is the other field token right this is very interesting if I'll run and I will show you the behavior or the response of this endpoint you might get the complete picture so here simply we are just getting the token okay once you are getting the token this is the method reference signature we are just calling the verify expiration method to validate the token expiration then since we have the refresh token object with us we are getting the user info from the user info we are extracting the name by passing it to the JWT service to generate the access token now we have the access token and we have the refresh token we are returning it back okay or else I want to throw the error which error any any custom error you can provide but for now I will throw the runtime exception so we need to build it while returning it if you are not getting anything simply throw the exception that the token which we are trying is not there in our DV user might be trying with the wrong token ID okay that's it now we will not force user to authenticate for this particular endpoint so you need to bypass this as well the way we have bypass for login and sign up similarly you need to bypass all the requests coming with this URL to not authenticate okay copy this endpoint go to the config class let me Zoom this very simple what you can do just Define your endpoint we're telling to Spring Security if request is coming with Slash product slash refresh token then don't authenticate that simply bypass it so that I can give that flexi to the user he will regenerate the token okay without re-authenticate so let's verify it quickly before we run our application for quick testing what I will do I will go and change the initial expert time of our token okay otherwise again we need to wait for three minutes for the uh what is that to generate the refresh token okay I'll make it 2 okay re-run it so it started go to the postman we don't need to add a user again because already this user is present in our DV now just run this we are getting a new access token and we are getting a new token ID so first let me verify the time expert time for this specific token paste here it will be experiment 55 I mean up to one minute okay new to two minute because 55 colon 56 so meanwhile what I'll do I will just pass this particular token to access the end point you're getting the result still we need to wait for a couple of seconds to expire the token meanwhile I will show you in the DV as well so the second token is that this was generated and assigned to the user that is how we did The Entity mapping so let's verify whether it exit the limit or not no let's wait for a second to expire this token then I will show you the error and we'll try to regenerate the token okay I'll try and serve 56. so it takes it the time let me hit the end point we are getting four not three if we check in the console what it says JWT expired at this and current time is this and difference is this okay it means it is not valid now now I don't want to re-authenticate again and again since I have implemented the refresh token mechanism then how I can do that I will simply go to the this this particular apical and I will take the token value okay now what I can do next simply let me create a new request which will web type post http slash products okay refresh token this is what the endpoint we have defined right then go to the body go to the Raw it should be Json here we need to pass the input as a token because this is the post method give this token what it will do it will refresh the token it will give you a fresh token with the fresh token by extending the expand limit of it let's verify it send the request we are getting a new token here with the new token ID now simply you can use this token to access the API go here and try accessing using this particular new token we're able to see the response here we are not forcing user to re-authenticate we simply provide a new API which is refresh token API give the token ID and get a new token okay and also we said the when the refresh token will be expired okay that that time also you have set in our code go to the refresh token service you no need to hard code this as part of your code rather you can give you some external config file okay so this is not a good practice you can keep it external from your application okay and this is how you can allow user to regenerate the token again and again rather than re-authenticate okay do let me know in a comment section if you guys have any doubts that's all about this particular video guys thanks for watching this video meet you soon with A New Concept
Info
Channel: Java Techie
Views: 26,614
Rating: undefined out of 5
Keywords: Spring boot jwt, spring security, spring boot, spring security jwt, jwt refresh token spring boot, spring boot jwt referesh token, javatechie
Id: Wp4h_wYXqmU
Channel Id: undefined
Length: 33min 27sec (2007 seconds)
Published: Fri May 19 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.