[Spring Security] Mastering JWT with OAuth2 and JPA for Secure User Authentication & Authorization

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Namaste everyone so after completing the tutorial you will be able to uh see these seven API and in which you will be able to do a sign in you will receive a access token you will receive the token expiry token type username and you will also receive a refresh token uh in the form of HTTP only cookie you will be able to do uh you will be able to call uh the refresh token using this let me just show you I will copy the refresh token from here and I will put it there you will be able to receive a new access token as you know the access token is can expire in like 5 to 15 minutes but refes token is there for getting a new access token and refes token expiry is generally like around 15 days or uh based on uh the requirement of wherever you are working but it is generally for a longer duration okay so using this sign in you will receive the access token you will be able to based on whatever the roles and permission that you are having you will be able to access different apis uh so as I am uh logged in as an admin I will be able to access all the apis from welcome to manager to the admin API if suppose I sign up someone as a role with manager let's signning up let's use his API uh let's see uh okay so let's see if I'm able to access the admin or not using the access access token so I'm not able to it is 403 Forbidden but if you have seen uh if I can use this access token for this admin message I will be able to access the API uh there is also called a log out which is basically revoking all the access for the particular particular refresh token so if you will see I have in this signin API I have the refresh token here right using which I can generate uh the new access token so if I log out this refresh token now if I can now if I want to try the same right uh to get the access token I will not be able to get it so this this is a good tutorial uh I I don't see any other tutorial where you will be able to learn all four of them sign in sign out everything and with the refresh token getting astp only so please follow along I will be uh putting a GitHub URL open that in the readme page you have everything there so yeah let's start okay let let's also check uh the uh S2 console let me bring that here let me bring my S2 console here so that you can check the database so you will be seeing user info and refresh token so if I will run the user info you have all the for uh data right and if I will use the uh refresh token you will see for which user you have uh created so yeah so let's start so uh I have given this GitHub URL so you you guys can go there and you will come to this page my main purpose is not to write code line by line my main purpose is to to get you guys understand how refresh token access token um Works how you can use it in your application so we will follow I have I have write it down in like bit size steps so I will also follow this I will suggest you guys also to create U open un and follow these steps that I'm doing it here okay so first step is basically to start the spring initializer right so let me create one more page and copy this put this thing here okay let's start with the spring initializer uh we are going to create a project so 3.2.2 is the latest one here at Quil converted to uh o right and we are going to to create J token with O2 uh similar demo for JWT with o O2 so it's fine let's use the latest Java and now let's add the dependencies uh the first dependency that it says is web let's add web uh then longb then longb then value validation so web is for API longb is for removing the buet blet coding right and validation is for validating your dto uh we will be using S2 you can use post or whatever you want to uh for the easier purpose I'm using S2 let's use jpa for hibernate mapping let's use or2 resource server for the purpose of uh authentication and managing our JWT let's add the last which is configuration processor spring configuration processor so we have everything that uh we require yeah let now generate it so once we generate it we will have the gy somewhere let's pull the zip uh okay so now we have this folder here right let's open this thing in our intj let's open the intj uh file uh I'm using intj you can you if you want you can uh use any of the editor you want right but for backend I will suggest go for the intj itself so desktop gw2 let's open this project okay and again I will will be putting this in the half of the screen and put this thing so that we can see the steps that I'm doing right so again I'm telling like uh these are uh this is the best way that I found that in a shortest amount of time I will be able to make you guys understand this otherwise it will be a very long tutorial okay so I think everything is working fine let's start the application and see okay we found this error uh it is basically when sdks are not aligned with the uh with what we want okay so if you have Java 21 it's fine otherwise if you have selected Java 17 or something you need to change so let's start the application to see that everything is working fine yeah yeah yeah okay everything is working fine so we H we have these dependencies now right if you want you can check for the build. gridle file you have all these dependencies here okay so now the second step is basically to do the database setup let me copy this and I will explain step by step like why and what I'm doing let me convert this file to yaml file and yam file is basically easy to structure easy to write right so that's why I'm using yaml file so open this yaml file paste it so if you will see what I'm doing here uh is basically hey I'm telling that um I want to enable my S2 console you have seen right like in the demo where uh we are seeing the database so this is this is what making it enabled so database Source URL basically hey jdbc is2 in memory database what database we want at Quil TV username system administrator password word nothing driver class name basically jpa for spring jpa for hibernate mapping right and we checking S2 dialect so SQL true and here we are doing create drop um what it does is whenever we restart the application it will delete all the tables and recreate it so it is very useful when you are doing any PC or small demo okay but generally you should use update in the broad environment so but I will rather tell you guys to use uh any kind of database management system like liquid base or ply base for managing any kind of update we will I will definitely make a video on it uh if if you guys require it write it in comments so I'm also using logging level uh to trace to see that like for the Spring Security only for the spring security so that if anything goes wrong I can just uh see the logs and tell you okay now uh for the logging we also need need need need to have some user right I could have used inory uh data in memory user or something very simple but I don't want to use that because uh uh it will be a chei right so I'm going to use JP itself which is widely used for any kind of uh I mean user management uh if you have any uh if you're creating any application okay so let's see the first step uh user info entity go to Java this create a package called entity create a file called user info entity just follow these steps and you will understand the flow okay and now let me copy this whole thing put it here okay uh what what this thing import class persistence here also the same import persistence so what we are saying is hey data everything we are we we are going to tell that hey this is the entity right and the table name we are giving user info ID and this generated value is basically saying that whatever the best uh uh best way it is there for this particular database uh create the IDS so username we are using ID username and email ID and this email ID we are going to use it for uh checking that everything is fine or not I mean user exist or not or for matching purpose username and password purpose so here we are saying aable false name is equal to email ID and unique is equal to true so here also n Lael false and name is equal to password mobile number and roles so this is very important rule so rule can be basically roore admin and roore manager so these are the different roles that uh a user can have right and there's a difference between roles and permissions Rule and permission so okay so there's a difference between Rule and permission rule is basically saying that like suppose in your house your father is having some role your mother is having some role right and this all these roles involve comes with some sort of work that they do so these are called permissions so suppose admin adminn will have uh some uh role of writing uh but a user can just uh will have a permission only to read so but admin can also have the permission for write as well as read so this is the difference between Rule and uh permissions I believe you might have understood so um okay so uh it is done now let's create a user info repo which is here to uh some like uh to add these users into the uh repo right so let's create a package called repo and this add a user info repo file okay user in for file let's copy this let's put it here so now it is saying that hey user info repo jpa repository I'm using jpa for mapping right user info entity and the ID is long so now the third step is basically okay so Au creating the authentication object so uh generally when you whenever you are doing the login and all you have authentication object that is coming from the HTTP like from the UI uh which we match uh to say that hey user is good or not we are not directly sending uh the uh the user and password right so let's let's first create a config package called config and in this let's add this user info config so what it does is it basically implements user details and the uh the only task of user details is creating the authentication object right it has multiple methods that it uh implements like suppose creating the uh Authority uh so this Authority is nothing but whatever the rules that you have created here um in the form of a string right it is converting it in form of list so let's copy this code from here to here okay so let me remove this user info entity let's add user info entity here so we are taking the user info entity let's add required argument Constructor so that this final fill we can inject using the Constructor injection so let's add this okay now everything is looking fine so what we are saying that hey whatever the rules that we have in the form of a string which is there in the form of comma uh whatever the rules that is there right in the form of comma let's convert it in the form of in the form of array Ru admin rle underscore admin comma rule underscore manager if suppose somebody is having uh somebody is having two roles okay and it is possible okay to one person to have multiple roles okay now let's see user Infinity get password so let's put the password for that entity here uh let's use username 10 and uh for everything else we just need to convert it to True right we are saying that he is account non-expired true it is not expired account it is not a blogged account it is not uh account credentials has not expired it so we are putting everything true and is this thing enabled it is also true so if you want to I mean uh do the configuration of for yourself what these you welcomed with it but this is a small tutorial so yeah where is the error uh okay so now everything is looking fine right let me give in a space there a space there so now let's um let's add user Detail Service which basically loads the user uh from the database so that we can use it for mapping to our API to check that hey everything is correct or not what then this thing is doing this is is just mapping those user with the authority object which is very much required okay so if you will go here uh you you can you can read all these things and it says that into the authentification object right this is what that I'm telling so let's close everything close all tabs uh create one more user info config inside this Java user info config it is basically let me copy this okay let me first show you that uh implements it also has one more uh uh method that we want to implement that is load user by username so basically it says that uh and why we are using this instead of directly injecting it into your security config I will tell you what that means if you don't remember about security config but yeah why we using this so that we have a segregation that from which database which kind of database we are getting our user so right now if you want you can use mongodb you can use post you can use SQL Server you can use uh Google you can use whatever you want you just need to find uh you just need to implement a method which loads the user uh in the form of user details that is the authentication object okay user details is the AU object so what this thing is doing is uh this method is saying get me the uh user in form of in form of au object object so it is user details right so now we are just going to copy this we will put it here uh it is the same thing I mean like uh okay so it is saying that hey load the user load the user user info and find by email ID using the email ID right so let me create this method inside this our user info defo so if you will see here it is saying add the Missing Method so let's add it here we say that hey optional means that it can be empty right user in for user user info entity so we are we are trying to find the uh user based on the email ID and what we are doing again we are finding it by the email ID we are saying that okay whatever the user that you have found let's map it into the information config using this what this thing is doing is it is just returning me our user details object right so we are returning your details object which is being used here and and if I don't find anything I'm just sending a exception which says that hey user email is not found fine so in a sequence basically load the user map it to in the form of user details and how we are mapping we are mapping it into the form of uh this user config okay let me close these two okay the uh one more part is there okay to say that uh now we need to create the apis let's first create the a okay okay let's first create in the security config um okay so here we are saying that let's let's first create a security config security config is basically uh um a class which which which uh it's usually defend class but it's work and generally it is defined as a security config itself so it is the first class which interact with your API after of course after all the application uh spring boot application work and after all the creating of The Bean it will come to the security config the API when the application starts the API come to the security config and how it will come to this based on these annotations so here we have enable web security with the enable web security the DP API is always come here uh with with the help of security filter chain and it it checks that what uh we want to do with it so let me copy it paste it here and let me tell you what this what what this thing is doing okay so we are saying that uh hey we are creating a security filter chain okay and how this thing works API you do you do a API call with this API call uh it sees the URI so it sees the URI it will come okay so if the URI is starting with suppose API welcome message it uh it will come here okay so the API is uh is of like type this it will come here it will make uh the csrf disable we are not using csrf it is saying that hey when whenever you see the API of this format let's authorize it okay uh any any request which is coming as like this let's authenticate it so you not authorize it authenticate it and how we are authenticating it we are using user Detail Service and where we have user details service we have user Detail Service here right using the load by username so we will just use user info manager config the class where our user details service is uh is written so let me remove this form login we don't need it uh let do a static import for this okay now this thing is uh looking fine and one more you see one more yeah security filter chain that I have given is for S2 console and why I'm doing this things like because our S2 console if I will run this application now you will see you will not be able to see our S2 console let me uh run this you will be let me first uh uh I mean let me comment it out let's restart the application if I will just do local host S2 console let me connect it let me restart the application I believe it is taking the previous one okay delete from the S2 console okay so yeah so why we are doing uh why we are writing this for the S2 console is uh simply uh okay okay so here we have for the S2 console start here we have for the S2 console so for the S S2 console is basically we saying what database right so we are saying that hey um whenever the request of the type S2 console is coming here uh let's not authorize anything because we we don't want to keep on uh pinging uh the API authenticating it to see the S2 console okay and and here we are just saying that hey make enable the frame option like the I frame on which it is displaying so let's start the application and see what I mean by that so if you will see our uh table has been created right so if you will just refresh it so this is our I frame that I'm talking about so if you will see uh you don't have any user right so our next thing is to add the user so that we we are able to see it so I like uh let's create a command ride Runner uh to create the user uh in the config create a package called user config and in this let's add a uh this initial user info class and it implements basically command line Runner so command Runner basically whenever the application starts this will run right so let's implement this method it has only one method called wide run so I will just copy and paste this code let me copy this whole class itself so you will see that uh what I'm doing here is uh I'm taking the password encoder as well here which is giving the wrong if I will comment it why I'm using it here is basically to encode our password so let I will add it but let's see what else is there in this Wun we have user entity manager and this setting the username uh password role and email ID right this is all I'm doing and I'm saving this thing into uh user INF for repo in our repo right and we should be encrypting our password we should not directly uh put our password into text format okay so how I will add that if you will see here I have given it that also in the security config go again back to security config and see that hey our encryption is uh our password encryption is used by B Crypt in password encoder okay it is it is a standard if you want you can use some complex algorithm as well but PPT is fine okay let's close this thing initial info so now the error has gone so it is fine right now if you will uh restart the application now if you will just restart the application and go to the H2 console and here also you should see that the three user has been added so if you will just uh refresh your uh H2 console in this you will see that three user has been added right what else so with this user you want to access the apis right so let's create okay let's move all the user configuration here let me refactor it let me refactor this also I have moved all related to user in this user config okay so that like everything is much more segregated now let we need to create the API okay uh create a package called controller in this controller we have a dashboard controller you can give any name you know right like the class name you can give whatever you want to let me copy this whole thing here put it there and let's see what is happening in this okay so just controller as we are returning the J body right if if you if you are working with uh uh the front end you just need to write controller I believe you must be knowing it so request mapping anything any API starting with the uh any anything any request coming in the form of API obl something will come here and for this we have security config right that we just did that anything is starting with the API will come to this part okay so we are creating the three apis called first of all is by welcome user manager message and admin message and in this we are saying this pre-authorized has any role what does this mean so if you will see in the security config we have also added a enable method level security method level security does what it along with checking the authentication that you have that you just created that you have the uh admin and password is correct or not it will also check that are you having the correct roles or not you just created the user right you have the correct roles or not and that's how our authentication object works right so in the dashboard controller if you will see uh let me import this security Cod okay fine yeah so in this we will just check that whatever the user that you are having uh it is having any role for the manager admin or user not if you're accessing welcome uh API if you are accessing manager API then your role uh should be roore manager if you are having want to access admin message then role should be admin okay so basically here the authentication object is basically before you are getting verified you can use it here and it will also have the authentication do get authorities which you can read I will just show you in the API what does this mean this basically gets you this rule that you have given okay and principal is basically once you are verified then you will receive a principle object and how this thing is helpful if you're creating the UI you can just display it in the front end that who has logged in okay so now everything is looking fine let's restart the application and I will bring the postman here okay so you have seen the demo we have these API right so first of all let's start with the welcome message so in the O go to the uh and I have given this thing in the uh Postman also so this Postman complete collection is given to you so in the O you basically uh just write the API obl welcome message and let's do the basic o with the admin and this so if you're admin you will be able to access everything right so it will say that hey welcome blah blah blah admin admin uh come with the scope rore admin so suppose uh if I want to access manager API with uh uh basic or instead of manager I will just write admin adate admin.com let's see if you are going to access aom no no you will not be able to access it access it though username and password is correct why because uh the role which is mentioned here right uh only manager can access it so let's create let's give here manager atate manager.com so this is we are going to exit it so and let's see with the admin message let's do basic got here basic got let's send the message so we have this API over here in the database also if you want to check that uh if every uh if everything is all the three users are there or not so let's clear it user info then this state okay let's connect it user info and this so all three users are there so we are able to uh we are able to see the JPI and we are able to do the all the API sort of stuff right this is the uh second part let's add let's start working with the fun stuff that is the access token so now we will uh be creating the access token and for this we will be requireing an RSA key which is the private and public key generally I have written all the details here if you want to read in uh in detail like like you can read it here but what I'm seeing here in short is that uh this is the best asymmetric keys are the best way to encrypt and decrypt your GW tokens and what asymmetric means is basically you will have a public and private key for encryption and description instead of having just a single key and which is the industry standard uh asymmetric keys of having the both public and private Keys separately is the industry standard okay so we will be using open S for the encryption uh sorry for creating the RSA keys so if you don't if you don't have any openl installed in your system what you can simply do is basically uh come to this repo right and in this repo if you will go uh okay so in this repo if you will go to the source Main and uh resources and inside the search folder you will have the private key and public key you can just uh op open it copy this thing uh go to this project here uh create a folder resource called uh directory Sears SS and in this you can just this is this file is basically word private key let me copy this name here private key.pem create private key.pem copy this whole thing put it here and close it it is as simple as that like that uh but if you have the op SSL there is a way uh to write uh this thing and in a similar way you have to I mean uh in the search you you need to create the public key as well let me copy this and put this thing here uh public key. pm insert this let me close this this is fine right so if you don't have op SSL in I believe you should install it uh otherwise you can do in this way to create a public and private key okay I will show you one other way uh let me go to Spring Security uh go to readme.md file again and you can SK skipe this part right totally skip this part let me delete this let me delete this two and okay so let me go to the terminal and here I need to go to the uh search folder CD resources uh CD and here it is in SRC main resources uh let's go to the search [Music] folder and now uh I will just copy this line let me tell you what it it does it is saying that hey open and cell generate an RSA key with key and pair uh with encp with a file size of 2048 so it is created right ke is created now I will copy this I will put it again here and what it says it hey um again we for the RSA key we have input of key pair let's create a public key output okay so if you will see here we have a public key as an output now again uh I can use this key pair as a private and this public key as a uh public key right but uh we need a pkcs8 encryption file uh for our uh encryption right so uh let's put it here press enter we will receive our private key uh by it is not coming okay let me okay so private key is here let me delete this uh key pair now if you will see the private key is here and public key is here similar to what we have it is not the same but it is similar so your your code will also work so here if you want to read it is saying that hey I want P CSI format file uh we will have uh the key pair uh as we are giving it here and we have our output as a private key and we are not doing any encryption for our uh public and private key you can give the encryption but the problem will be like not the problem for this tutorial the problem will be it will ask you for creating the paraphrase and then that paraphrase you have to use it everywhere okay so everything sorted right if even if you don't have this openl it is fine I hope you guys understood okay let me close this public private key let me close everything now okay so now how we are going to use the these two for our encryption and description for our Json web token okay uh let me go down okay first we have to use this rsf public key uh public key and private key right so in the config let's create a file called RSA key record and it is a record right so let me copy this and I will tell you what I'm doing it here so we are saying that here we are creating RS key record uh I mean with uh the parameters of RSA public key and private key okay and we will have a prefix of JWT for the configuration properties so for adding this configuration properties are stayed in here right so for adding this into the configuration the properties we will have to go to the application and uh if you will see the error that it says it says that hey not registered enable configuration properties for our application so let me go to the application let's put it there and say that hey RSA key record RSA key record class is uh for adding our configuration so okay adding our configuration for this public and private key for our public and private key so let me uh if if you'll just go here if you will just write now JW JWT it will say private key right and here in RSA public key both are here let me copy this put it here and okay so we are saying that hey for the jwd token for the private key we have in the class path Sears we have a folder and we have a file called private key.pem and public key. PM so it is fine right if you will restart the applic appliation you will have this private key public key accessible to your application so now let's start the security filter chain as I suggested earlier what is security filter chain whenever the API come whenever there need interaction with the API it will come to the security filter chain itself right so what we are going to use this security filter chain so let's let's tell you how JWT works so when you are signing in right when you are uh sign in in the application you use your username and password right to sign in your application once you are signed it the application will send you the access token access token uh which will have Rule and per which will have all the permissions that you that you require to access your uh other apis like all the other apis data apis and all so when you're using username and password right it will be using this user detailed uh service to authenticate this and it will return the access token and this access token is nothing but GW token okay so let's design this sign in API I will just copy this thing and let me put this thing here and I will just rename this thing to sign in let me just copy this line sign in security filter chain sign in security filter chain and here I will say that hey if the user is going to sign in uh let's make of course let's authenticate this user using user details and this and I will make this thing session State uh stateless so what it means is we are not going to store uh this information and uh what it means is basically that for every request coming for signning you need to do the authentication we are not saving this information okay uh let me add this exception Handler also so here uh HTTP if there is any exception I mean if there is any problem uh occurs while authenticating or anything we are just uh sending this message like is creating this exception it is fine right so everything looks correct let me remove this thing also so that it doesn't confuse you so you're understanding right why we are doing sign in with this where this Suess token goes this will come after this step so after sign in everything is correct it will return the access token and using that access token we are going to uh access this these all these API okay okay so now our next step is to create the signin endpoint uh let me go to the project uh it is saying that or controller right let me copy this name uh let me go to the controller let's create a file called or controller here we will write our all the authentication endpoint like sign in sign out uh login like I mean whatever it is there okay so here we are saying that he sign in and for this security config we have here right so for the sign in we are using user Tails manager service right so let me import this authentication object here okay so what we we are basically this endpoint will uh return the authentication uh object right like whatever you require and what we require is basically uh let me create this file let's create a package called dto and and in this I will write Au response D2 Au response D2 let me copy this put it here so uh there's a token type let me add token token and let me explain you what everything is and here what token type is be token let me close this thing o controller so as I said whenever you are going to uh sign in right to whenever you're going to sign in you are going to get the access token JT access token right using which you are going to access the API so how you are going to get uh uh how you going to get um the access token uh we just created object called aut response D2 and this will have this access token uh the expiry and what does the expiry mean if suppose you are hitting the endpoint called API right if you're hitting the endpoint called API and you have the access token whatever the access token is you are having uh it is only available for 30 seconds now since you received it uh plus 30 second you can access this API so this is a security feature basically so that like um uh uh you you are suppose you are going to the bank website or somewhere there is uh when you logged in and if you went out from your screen right if this expiry is not there then till the time you log out uh your banking application is continuously open it is not a secure thing right so in this way how we can Safeguard is basically to give the expiry of suppose 1 minute or 2 minute uh so that like uh even though if you have left your screen open um after 1 minute or something something nobody will be able to access anything from your application right so this token type you're basically just saying that hey what kind of token we using we using be token for the Json web token and this is the username that I I was talking about that is useful to display for like who has logged in you can add different things here that his image URL or whatnot which is there from the database okay but for for our purpose this thing is fine okay you understood right what is the O response dto okay let's go to the O controller uh one more thing that we require here is au service right so what in the Au service we are doing we are writing all the business logic and what business logic we are doing get JWT token after authentication so once you re reached here your authentication is all done right because uh we are already bring up authentication here right so once you have the authentication you are returning this so let me create a service package called service here just write o service o service so okay let's create the method there okay now we have this method there let me copy this file let me put it here I will explain you uh what this thing is do again right so don't worry about this thing first of all we are saying that hey um uh in this method right like as you saw that like we are calling this method to get our access token we are seeing that hey this user whoever the user is get every details about him from the database so if you have seen right from the database it is getting all the details hey if if the user is logged in as a user what uh what other details details is they having so we are having role and username and whatnot so these all are coming into the user info entity using this uh we are uh we are basically creating a uh using this we are basically creating the access token right so let let's see uh let's see how we are creating the access token so yeah sorry one more thing uh whenever you are loging right as I said like this is the authentication object earlier I explained you write like different authentication object and the principal object so once you logged in this authentication object is coming here this authentication object is nothing but the user details itself so if you are coming here we have this user details and uh this is in the form of authentication object right which is being used to create the ACC access token so let's create a file called J token generator where we will have this so in the config let's create a new package called JWT config okay let's me put this thing inside the config itself refactor and inside this let's create a g token generator so what its main purpose is to generate a token token generator let me copy this let me put this thing here and I will tell you what this thing is doing okay so we are uh we are saying that hey um in here we are seeing that he using the authentication object for whoever he has logged in generate a token so if you will go here let me import this authentication security code so we are saying that hey let's get the role for the whatever the user that I'm having here so get role of basically it is again uh let me okay so get user R from the authentication so authentication that get authorities as I as we have seen in the demo right so let me so in the welcome message this rule admin is the authorities right so if you will go here inside our uh demo controller so authentication do get authorities is our role which we have in our database also right like these are Ro so in the token generat we are saying simply that hey let's get the authorities right and right now our authorities are in the form of what in the form of a string right with uh sorry in the form of arrays so and why I'm saying in the form of arrays because we have the user details right the class so if you will see in the user where is that config user info config we are converting uh the user details in the form of this right authorities so now let me minimize it go to this access token we are saying that hey let's get the role in the form of a string so why in the form of a string so let's get the all the authorities uh because it is in the form of uh uh I mean arrays right now and let's convert into the form of authority whatever the not convert let's map everything whatever the uh roles that we are having in the form of array it these are all the rules and let's create this based on uh let's create it in the form string so here it will be form of suppose rore admin admin with a space if you have multiple roles rore manager so from here we are getting the array here we are getting the uh in the form of a string we are going to use a string that's why okay and let's with the rules as as I explained earlier between the roles and permission right so every role can correspond to multiple permission so let's convert uh the role in the form of permissions what kind of permission that we can have so if you have a role admin you can do read right delete if you are a manager just read if you're user just read you can definitely append whatever you want to and we are creating a set here why because suppose if you have role admin and you will have a manager and uh you will have a list of permissions then read will Multi like replicate right read is here read is here to to remove that and to return a simple uh string with just the space uh we are using this set so now we will have read if suppose somebody is admin as well as manager uh the role will say that read a space write a space delete itself okay fine right so now we have the permissions now what we are doing it here this is our token creation so this token is being created here here which which is called claims and here we are saying that who is creating this access token or whatever the token is being created it is being created the by the application called squl you can write whatever you want and what what time it is created instant. now now it is being created when it is going to expire so now whatever the time it is there plus 15 minutes so as I said access token is for very small durations it should be for very small durations so that nobody can access it refresh this to refresh token is there for very long duration which will in turn return the access token I will explain it later don't worry so subject is basically uh the user name like for our case it is the email ID so we can we can write here not get uh okay so authentication get name is basically our email ID don't confuse it with the name so here whatever you are doing it for the login it is coming as a get name so this is what this is the email ID okay claims is basically what kind of U permissions that you are going to give for that particular uh person so in our case the these are the permissions that we have okay so uh and let's build this whole thing now we are saying that we have created digital rouy token let's encode it so that uh when we are sending it back to the user right when we are sending it back to the user it doesn't get hacked or something okay because we have the encode like private key and public key so for encoding decoding we will have to follow the encoder and decoder right we uh let's add encoder and decoder into our security config let's open the security config and this encoder decoder is coming from where from the open SSL encryption for the RS key that we did right so let's copy this and we explain you what we are doing it here uh let's import this from the Nimbus okay and let's copy this RS SEC cord okay so now we are seeing that uh first let's encod it so we we are encoding uh uh whatever the values that we are receiving so what we are receiving it here in token generated we are receiving the claims and we are saying that hey incode this whole thing right we are encoding this claims so we can encode basically everything but here we encoding our JWT token and what we are doing a security config here we are saying that hey we have a we have a public key and we have a private key for this and using this let's encode it okay what we are saying we have a public key we have a private key let's create object and with this object let's encode it into J using the nus encoder in the similar way as we are using Nimbus right let's decode it using the public key so we are decoding using the public key but we are encoding using the private key for the security purpose right so now we have created the bean and how we are getting this value using the private P RS key cord and this RS ke cord we have in application. EML right like uh so here are the keys understood right let me close this this and all controller we are going here we are generating the token and now whatever the token that we have created we are returning it back okay everything seems legit and fair now one more thing we need to do basically uh in not in this in demo controller so if you see that we are using has any role so role is basically when we are using the authentication purpose so generally for the method level security and when we are using the Json web token we use Authority instead of roll so if I will use this it will throw error let me show you oh oh oh oh oh just just a wait a minute uh let me go to uh GWT token generator and we are using it here right oh yeah I was about to explain you here this sorry so now we have the access token here we are saying that UT response dto right in this we created this dto right to return to the user so in this wait uh go here uh this access token let's give the access Tok can we are just telling them that hey expire is for 15 uh 15 minutes so 15 into 60 seconds so it will be in the form of seconds there in for the user username is basically from the user entity we are giving there token type saying beer so everything looks correct right so let's restart the application again and our main purpose is to see if we have the access token or not so if we will just uh do the uh sign in we have signin API right that we just created if we will do this we are receiving the access token let me copy this access token uh let me go to uh we using admin right let me go to the manager and let's change it to beer token let's put my access token there and we are not uh able to get this API value why because we are saying that uh uh let's go to demo controller we dashboard controller sorry we saying that has any role but this doesn't correspond to any role this correspond to Authority right so let's copy uh this has a new Authority scope of read uh scope of read let's look at a scope of right let me comment this thing comment this thing these are called permissions right so and how this is coming again I'm just going to show you in not in user config uh in here yeah while generating the token we are converting the roles to the permissions so this is fine right rules and permission is done okay if you have any doubts please comment and I will explain you okay so now let's restart this okay one more thing we need to add sorry sorry I forgot so uh in our security config uh in our security config we haven't told yet that like hey uh this API whatever the API is there uh we have to use the JWT token right the access token to access this thing so for this let me uh these are all fine authenticated instead of this we need to use the o server let's copy this this this and this so this is very similar um okay these are the logs let me just write here SL 4J so that our logging is correct so we are just saying that hey uh we are using O2 resource server that we uh imported right uh I mean while building the uh application this dependency was there we are saying that let's use JWT with defaults for authenticating our this and we are not managing anation uh which is the stat L it means basically that uh you for any API call you again and again have to give the access toen okay so this looks fine and it is one let me convert this order to two let me convert this order to three and yeah let's restart the application so now if we are going to give the send we are going to see the sa and now your question should be why even after restarting the application the same access token that I created I mean back is working fine so this is The Wonder of I mean not only Wonder this is the security flaw of access token as well even though uh your application restarts even though if you will just delete the user let me just delete the user uh let me go here uh not this one this one is done so let me go this loaded so connect again so this access token is being uh created by the let me create the exess token Again by by the Admin right so using the admin I will just copy it and I will admin uh use the admin message to get the value let me change it to be a token let me put the access token here I'm getting this value right so let me delete this admin itself so in the user let me delete this admin so ideally what should happen uh if you have used to used um uh suppose for authentication if you have used this user Detail Service it would have not found the user and uh uh the API call that we are going to do here would have been invalid but as we using the access token even though if you have deleted the user if you have the access token and it is not expired you will be able to get this value so that's why it is little bit scary right because it has all the information that is required to be authenticated that is the reason we need to keep it as expiry as like 1 minute like 5 minutes 10 minutes something like that okay so your next question may be coming to your mind that like what happened in the log out moment so when you do the log out basically you remove this access token from the user browser cache from wherever you have stored this thing use access token and if you want to added layer of security then you need to keep a blacklisting the access token whenever you log out so it is it is not for this course purpose so let's go get let's gete okay we need to work on so many things now okay so we have tested this thing now add what is this JW filter is so as I just showed you right even though the user is deleted it is working fine so at least let's safeguard that part using the filter so filter what it does is whenever this API request comes in uh whenever the API will come in here it will see the J J token that you have and it will it will do some sort of validation uh for once it is also it will also check if the user exist or not if you want to add it there so let's add G filter okay so let's add first this J token filter uh inside our J config token filter here added let me copy this and I will explain what this thing is doing okay uh okay okay okay okay now okay uh don't worry about this we will we will we will see what this thing is doing so basically it is doing l login and yeah now uh whatever the uh request that you are sending right uh you will have uh a URL right so that URL you when you sending you're sending with the access token like like how we saw here right this is the access token if you will expand this as a code this is having the header which is having the authentic uh authorization right and with having the pror as is starting and with The Gap and uh this is the token right so what we are seeing here is let's get the O header so what is the O header the authorization that we just saw this is the O header whereever this is the or header this value it will receive so when it received this value uh here now with this sorry for that now we uh just skip this line uh for now okay so we we are just saying that like hey this OD that is having the beer as um I mean starting point or not it start with be or not if it doesn't start with be maybe the token itself is wrong so if it doesn't start with the beer it means the token itself is wrong so we will just refuse to accept any other process on this if it is correct then we are saying that uh that hey whatever the uh uh whatever the thing which is there after the seventh word of this o header is a token right Jon web token that we are having so let me count one like here 1 2 3 4 5 six and with the space seven so give me this this is my token this is my access token so let me open this this is my access token right that you just saw and with this access token let's convert it into the form of JWT itself so this JWT decoder right and how this decoder is coming we have the RSA key record right that we just created coded and decoded so we just encoded it and now we are just decoding it so if we are coming here we are going to decod code it in the form of JWT JWT decoded or decode whatever the string the token that we are going to have it here okay now we are also now we need to just get the name out of this token so uh we are creating a g token utils so let's create the J token utils it will be helpful so in this JWT token U so let me go down here copy this so okay import this JWT to yeah okay we will come here like we will go in a sequence by itself so we are saying that hey uh what we need to get we need to get the username uh from this why we need to get the username so that we can check that if this user exist itself or not but for whoever the token is created witha like we just deleted the admin so we are we need this admin added admin.com from this value this token value right so that's what we are doing it here we convert in form of JWT and we are going to get the username so how we are going to get the username it is simply having a uh I mean method in built method called get subject so simply um so why we using Z token UT instead I could have just directly us like G token here like suppose a string xal to G token. get subject here itself right but uh so that like whatever the function that we are doing on the G token we can do it in a single file so it is called separation of concern is a much better way okay this uh this method is only work should be to generate a sorry to filter it out filter the3 token right so let's get the username and if username is empty uh then we are just saying that like hey this us doesn't exist and uh we are not processing anything so if the user is not empty if the user is found and the security context holder is not equal to it means that you have once uh you have the authentication object right uh if if it you doesn't have then also it will done as null so you you must be having some sort of uh authentication object here once you have that you can just check that this user exist or not so if you like user detail like user details so let me convert so first we first of all we are creating the user details user details is what is the authentication object right as you can seen uh where we have used okay let me not we have converted our user in to user details right here in this we have converted our user in entity into user details right same thing we are doing it here we are saying that hey in toenails for the US username this find this thing in the repo and convert the in the form of user details so we are saying that user info repo in the form from the user info info uh just find the user convert into the user info config and return me the user details we could have directly used load by username also but uh both are fine okay and why I'm seeing load by username if you will see here this thing is also returning user details based on email ID right so if you will see both methods are doing uh the same stuff right here both method are doing the same stuff so but it's fine uh yeah it's fine let's go to here okay so now we have the user details object this is the authentication object for our user info entity where our all user details is there we just saying that hey uh can you check check if token is valid or not for this jwd token that we have here and for this user details let's see what this token is checking first it is checking if username uh is there or not so string sorry whatever the username is there we are receiving it here and now with this username it is taking that is this token uh is even there or not like in our database so whatever the user uh we have there in uh I mean whatever the user we have and whatever the from the token that we are receiving I mean database we are receiving is both are same or not like suppose from the token we received admin rate admin.com is it same from the user details or not because us details is getting from database and uh this username we are receiving from the token both are same on is token expired is basically checking that what is the expir date on that token right we have on the the token whatever the expired thing is there so we are seeing that hey if token is not expired and if it is whatever the user it is same in the database as well as in the token then uh return true okay so this token is valid so token is valid so if token is valid uh let's uh create a security context holder and add our authentication object what is the user details into it okay and let's return our uh user details with the complete user uh let's set the security contact center and return our uh request response with the user with the authentication object so this whole thing we are doing here so if you will see this is the uh last part okay and uh let let us go to the security config I believe we have done the security config thing yeah we have added all two resource servers so let's start start the application and we will do this same thing again let's uh as do the signin for the admin we have the access token let's log in with uh I mean get the access of this admin message using this let's delete this admin uh if you will just uh refresh it connect it see the user info you will see admin is present here let me delete this admin now uh you should not be able to access this in earlier we were able to okay why why this is uh accessing it so okay so the problem here is we didn't even add the filter here right though we have creaded the filter we haven't added it so let's add the filter let's copy this whole line let's put it after this and we have just saying that hey add the filter before whatever you are doing the ODS server whatever you are doing at the filter before it we have the filter called token access filter which will have the RS ke cord and J token util let me add J token M uh let me go with this and let me put it here so we are just saying that hey uh before doing anything let's add the filter here uh a key record with token utils uh and it will have us user name password authentication filter uh so that once you receive this everything should be fine let's restart the application again and let's refres this thing let's connect this thing user info in this let's see uh okay so it might have expired so let me sign in again let's use this API okay I'm able to receive this now delete this user called admin and I hope it should not okay it is giving the error perfect fine right so at least one thing that you have averted if you delete the user and if suppose in future you have uh some logic that you want to put you can uh put it in the user info entity table itself and you can say that a private call like I mean logged out or something which you can update whenever we have we are logging out you can put it here and in the filter uh you can basically check when we are doing the valid validity check here right where when we are doing the validity check here right here you can also check that if uh if it is not expired then uh let's also check that if the user is having I mean uh active or not something like that you can also check it here okay so I believe uh it is fine if it is expired you're checking there so it is fine right okay so now uh the next part is for the refresh token and I have written something here let's read it uh access token is basically used for for authentication I believe I need to correct this it should be for authentication not authorization uh please uh it should be for authentication and refreshes token is for um oh no no no sorry uh I was right here access token is basically for authorization uh once you sign in which is call the authentication um you you need to get the permissions right like what what kind of API that you can uh do activity on so it is for the authorization and reference token is basically to get this access token okay so access token is shortlived and this is called this is long lived and uh generally uh basically in the responsibility you can return it but refresh token you should return it in the form of HTTP only cookie and it is the industry extender so let's work on it so we generally stored our ref fresh token into our database so that uh we can always match that for the particular user if whoever is there uh whenever he sending the refresh token uh is it valid or not this is for double validation right uh so let's create an entity entity uh let's create What entity Cod refresh token entity Java classess token entity let's copy this put it here so should be fine yeah so what what values that we are having here same thing right entity table Builder whatever table name is repace tokens so generated this I explained okay so now we will have a refresh token stored and for one user can have multiple refresh token and what I mean by this is suppose you have uh suppose you're creating application which is integrating with multiple different application like you have a Google Google account right so your Google account is connected with your uh suppose your Uber Ola or whatnot so for all those application uh to get access to those application those application store a refresh token so differ token is getting for the access token right so for this purpose generally it should be uh many to many if you you want a user to have multiple refresh token associated with different application okay and Boolean revog is basically saying that is this refresh token which is there is it revoked or not did the user sign out uh or not if it is signed out if it will be uh true so we will not be able to use that particular refresh token okay and here also please see that here we have given the string length of 10,000 so that we can accommodate dat whatever the refresh token we have so if you have 2048 bit size length uh for your R key so that if you have 408 uh something you should increase this length here okay I'm forgetting the length size 2048 and 484 something like that is there okay so this is for storing the refresh token and if it just for minut to one then we will I also have to change the user uh where is this user INF entity to add many to one relation uh sorry one to many relation it says that simply uh one user can have multiple refresh token and user F typ lazy so that uh whenever you are extracting the value for the user this doesn't come along okay let's add a repo uh called refresh token [Music] repo uh it is interface let me copy this put it here so everything is looking fine okay it is for the mapping now it is say that he create a refresh token generator so uh we already have a uh token generator right in config you config token generator so in this token generator we are generating what we are generating the access token let's copy this and we need to create a refresh token so generate refresh token process is almost same so in refresh token we don't need rules and permissions uh whenever we are Tak generating refresh token generally you could you could have you can leave this thing blank but I prefer to give a space permission that is called let me copy this refresh token and why I deleted these roles and permissions so that using the sees token should not be able to access any sort of data apis right so let me copy this log as well and let me convert it to 15 days instead of minutes days so that uh within this 15 days you can like this token will be active scope is fine encoded encoded generated PR token it is all fine now with this refresh token we need to uh we need to create the API right like we need to modify the API to send this refresh token along whenever you are doing this sign in right so so let's go to the or service uh not o service or yeah all service so whenever so what is happening now as I said whenever you are signing in whenever you are signing in you will receive access token access token in the response object and you will also receive a refresh token refresh token uh without permission permissions uh to access other apis to access data API in HTTP only cookie which you can use to get the access token right so let me remove this I hope you understanding of exess token refresh token is clear by now okay so what we are doing here is this is being used when we are doing signning right so here we need to return the uh refresh token so I could have just added uh a one more like one more parameter here refresh token but uh it is and I believe most of the tutorials is saying like that itself returning here but it is not advisable we only use HTTP only cookie okay so that from the UI it is just little bit safer for any kind of hacking attacks okay so let's modify something here let's add say that hey let's add a refresh token here because we already have any token generator refresh token right so we will have the refresh token now this refresh token needs to be saved right uh first this refresh token needs to be saved as well as create cookie so let's first save this refresh token in our database so that we can match if refresh token is uh Ian I mean for the future purposes so let's create this method uh create this method here is this method let's copy this put it here rep too is needed let's add private final replace token repace token rep replace token repo replace token rep so what we are doing here is simply uh we are creating a ref token entity and we are simply saving it it's ROK false revok means like if you're logging out then you are making it true right so we are sending the refresh token value we are saving the user info entity and we are saving uh the refresh token so if um now we have saved the refresh token now let's create the cookie so let we have created a a method uh let me okay so yeah for adding the HTTP cookie uh what we need is the Sol lit response object so let me go to this let me add one HTTP solid response uh yeah solid response this this response object we need so that we can return the cookie so let me go to this here also let's add HTTP Sol response response so let me put this thing here right here so this HTP select response basically detend the uh the uh cookie object right so now we will create this method called create refresh token from cooking and let's create this method here I will just copy this and explain how this cooking is being created uh it will be so hdp okay perfect so now this cookie is being created with uh the name called refresh token okay I'm saying that HTTP it is HTTP type with uh uh true it is a secured one and for how much time it is there for the scopy will exist it should be similar to your refresh token expired date so it is for 15 days that is 2 4 multiply 24 hours 6 24 hour is one day right into the 60 Minute into 60 seconds so it is in seconds right so I'm calculating with it for the 15 days and we have Set uh uh for the refresh token expiry also for 15 days right in the our token generator where is that token generator G3 token generator here we are setting for 15 days similarly right so o controller let's go to sign in now we have cookie ready so this whole process is now done uh why this thing is saying make method wide if you want you can make the method wide otherwise uh it's also fine like in solid response also is fine because we are not using its return value we are just setting the response object right so let me show you where this cookie exist if you're using the postman so now you will do the uh sign in you will see in the cookie you have let me remove this let me do it again if you will see here is the refresh token so in this refresh token is there this refresh token is not the access token as I will show you here using this you will not be able to access any of the API okay so this refresh token is needed to get the new access token so let's now create an endpoint for getting the access token so in the O service and the O controller where is controller o controller let's create the API where when we send this refresh token it will give us the new access token so let's see I'm saying that uh the refresh token should have the authority of scope underscore refresh underscore token we have given right refresh token so let me decrease this thing to 1 minute so that you understand the benefit of uh refresh token right so in 1 minute this access token gets expired so one minute is very uh uh short duration right so in this short duration this will expire we will use refresh token to get the new access token okay in the O controller let's create this method generate X rate token using the refresh token so let me copy this thing from here to here okay so let's see what we are doing here just gener token using the refresh token we are getting the authorization header let me see what this authorization header is we are just getting this value uh authorization header is basically here right like I show showed you this is called the authorization header so we just get we will be just getting the token value from there the refresh token value from there okay so we will be getting this token value here and we will be sending it to our m method where we will first check that for whatever the user we are sending this is it even there or not is it in the S2 console if I will just uh clear this uh if I will refresh this you will see refresh token should be there refresh token is there right so I'm just want to see that for whatever the user it is there if I'm sending the refresh token is it even present in the database or not if it is present then and if revok is true sorry if revok is false that is he is not logged in return the new access token so that he can use that access token to have the values from the dashboard apis okay so let's start with the authorization header we are just checking the authorization header should start with the V name if it is not then return the error we are just getting the refresh token similar to uh here right uh similar to this uh where is that okay any like we are just rning the sub string for seven like be after B the space and after that token is there right so here we are getting the refresh token using that and we are finding this refresh token in our database so uh if whatever from the database is the user ID is to so what we will be doing is Let Me Clear user ID user4 and user ID 2 so we are seeing that whatever the refresh token we are sending is it the same user which if it is the same user if user is there right if user is there is it the same user that authentication is given I mean like uh from the token we are getting is both are same or not so let's do find by refresh token let's create a method uh here we will write optional WR refresh token entity and now we are finding the refresh token from the here right we are finding the refresh token we are seeing that is it rebooked if it is not rebooked then give the value otherwise say that hey whatever the refresh token that you are sending me to get the access token it is rebooked okay please uh sign in again or whatnot now from this this refresh token entity that we received let's get the username and with this username let's create the authentication object now we have to create the authentication object right so using the user info entity so there's a method called like we will create a method our own method here let's copy this paste it here so what we are doing is for creating the authentication object is getting the user email ID password and the role this is very important role and this role we are converting into the form of granted authorities that we have right so role is in the form of string that we have right so those string like to remember like in our database the roles are uh in the form of a string and separated with the commas so we are converting into the form of again arrays and this array is converted form of the uh author and we are passing the username password authentication token I mean this is the this is the place like uh I mean uh this is the method which will return the authentication object so using the username password and whatever the roles that we are having okay so using this the authentication object is returned and we are sending to generate the access token uh using already existing method called generate access token right this we understood previously so now we are done okay add also the helper method in the DPO uh this we added this helper method in DPO right okay okay yeah now we need to create a security config uh where is that in the security config and why we need to add it here um so that the whenever we are doing the API call for this SL refresh token right uh it will come here to this filter chain thing and see that if that refresh token is existing there or not and then return back the exess token so right now we have this let's create for refresh token and let me change it to four okay what we are doing here is simply uh uh I just like B basically both are same except we haven't added yet the filter uh we can add the filter or it is uh optional if you want to add you can add we will add okay as it is there itself and you like now also it will work if you will see that we are saying that hey we're authenticating using the j3 token itself which is basically the refresh token but we will not have any permission with that and everything is fine if we will run this thing I hope the refresh token thing should return at least the access token let me close this thing let me do the sign in if you will see here we receive the signin API let me do the admin thing so now we are able to access it right let's count for 1 minute let's see that uh so it's 12:57 right so we will just wait for a few seconds I will pause this thing so just uh I'm just waiting for it to get failure right you can uh please forward this little bit it is almost 45 seconds I believe it should expire anytime now come on I will pause this thing video so I believe it should fail now because it is almost more than 1 minute so yeah it is failing right so now what we can do is by while we are doing this sign in we must have received a refresh token so using this refresh token let's see that if we are able to get the new access token or not so where is the sesh token API I will put the this thing we will receive the access token wonderful and now let's do the admin message so yeah perfect right so this way you don't need to log in and again again every other minute right so refresh token helps in that way so refresh token what it did though your access token expired right uh you are able to uh call the refresh token method based on uh what you received in the cookie you are able to call theace token and get the new access token so it is a cyclic thing and till when it is will happen either you log out or till you basically um delete like evoke your refresh token okay so one more thing uh in this is to add a refresh token filter uh and uh if you want you can add it it will basically check that if uh the user has roked or not so let's add this thing itself it is pretty simple okay first create a Jess token filter let's go there and a GWT config Java GWT refresh token filter let's copy everything paste it there so let's see what is happening there so we are seeing that uh whatever the request is coming in uh same thing like take the Heather uh convert like we will have a first we will we should just check that hey if it is starting with be or not and then we are going to take the token uh based on I mean like after be 7 right now you guys understand this the same thing here uh let's decode the token based on the RSA key that we have uh let's get the username from the token uh let's see that if username is empty or not if the context itself is n or not authentication object is self present or not so we are adding one extra method in this what is this we are just checking in our database that whatever the refresh token that we have here is present there in database or not and if it is present is it red so if you will just uh do the quick reload connect the refresh token so we are just saying that is it revoked if it is not revoked then it is fine right so this is the extra thing that that we are doing okay so about this and now we are checking that it token is valid and plus if uh uh token is I mean refresh token is present or not so we are adding just this thing extra just everything is same okay so that's why I said like it is pretty simple let's add it here itself so in this we will just have to add this add filter let me add here and it needs refresh token repper let me add this refresh token repper rivate final rep token re repace token re I hope you guys are understanding till now uh if you're seeing this video uh uh because uh you can guys can pause also time stamp and all to see that uh everything is working fine for you or not I mean like you can just can divide into a chunks and then do it or you can just go to this repo and copy this and paste the steps okay so let's start with this sign out okay so sign out will do what it will revoke the refresh tokens so that nobody can access it uh to get a new access token so many access right so what we should do is for the sign not the Spring Security provide uh a internal uh I mean Spring Security has internal method which is it called it logout Handler so it is pretty cool let me copy this thing uh let's put it here change it to 4 it is fine let's change this thing to so what these means is basically the order of creation of be so uh whichever is having the lowest one will have the highest priority okay so it is similar here what about the whenever you are pressing the log out API it will come here CSR of disable we need to authenticate the API that every uh person who is giving this is correct or not stateless and add filter basically uh let me remove this thing okay um we can check because anyhow whenever somebody's logged in then only uh uh he will be I mean he will be sending through the exess token itself like it is fine you can use refresh token also to rework it but both are fine so we can use the refresh token one also it both happen so uh with the log out and and you can even remove it if you want to so this is the thing which is coming here which is the Spring Security in buil functionality which says that Hey whenever this logout API is called let's add a logout Handler a service method so this is and once it is successful let's remove the authentication object from security context folder so let's do whatever we want in this logout Handler let's create a file called logout Handler service I'm just going to add it here and then create it being a little bit feeling little bit Macho kind of thing okay so in this service let's add a file called logout Handler service okay and in this lout Handler service you basically uh saying that hey uh let me let's reload everything okay so it what this error is okay Handler service we we are saying that and these are all the inbuilt inbuilt method so let me remove this then you will understand what I mean by that so log out handlers in the security config when we added that hey our logout Handler will be there in this me third right and this here we are implementing our logout Handler which is given by the logout Handler which is given by the Spring Security and it has one method which says log out log out using the request and response and for the authentication object okay so let me copy this back again put this thing here so once we are having this request response and authentication object let's see the the a header yeah it is the authorization type we are seeing that uh if it is not a beer it means that somebody is messing around with us we will just return it without logging out uh we are not doing anything uh for this request uh and we are just taking the spring refresh token and we are just finding that if this refresh token exist then simply uh set the token value to roke is equal to True okay and why I'm doing this map here because suppose uh uh because it's many to one relation right so that's why we are having it in this way you can see I have also added one query here right which is if you want uh to log out based on a specific like from the all the refresh token uh using the email ID ID you can use this query here find all refresh token by the email ID and delete it but right now what we are doing is we are sending our refresh token here itself right uh to get logged out so it is one specific one so that's why uh it is much more simpler did you get it what I'm saying I'm just saying that right now we are sending the refresh token for the log out right so when we are sending this refresh token to the logout it is coming here only one value will be there because this thing is unique so we are just deoking that value and saving it and making it true okay so once it is done let's restart the application and now we will see uh I believe uh let's do a sign in okay uh we have this let's go to the cookie refresh token let's use use this refresh token to get new access token uh refresh token put it there new access token uh we are able to get this access token right and if we do the log out with this refresh token it is coming success now if we will try to get the new access token just saying that hey it is worked right we not able to get the new access token here if you will see in database uh so let me reload this thing connect refresh token if you will see deok is true so now our refresh token is roked and you will not be able to get a new access token okay perfect right so now we have reached to the last point where we are adding the user which is the sign up finally so if you are are still here so you are uh you are a legend if you still sticking to this tutorial this long so for this sign up we need uh some dto right like uh so let's create a dto in this dto let's create a user registration D and this let's put it there okay not empty is basically you can't put null or anything uh I mean with simply you can't put a double braces you need to put at least some length there okay this is called not empty it is different from the null and the these are coming from the validation that we require right validation object so validation dependency that we had so this is very useful so this is our uh registration D that we require let's create API called sign up API let me copy this uh the O controller let's create a last one called sign up so let me do this and so here what we are doing we are seeing that hey uh whatever the request body user2 is valid or not and this binding result is basically is being used to uh for the validation dependency we not that like email is there or not or uh something is n or not not so this is being used for that so what I mean is these things these things are being checked there in this finding result okay uh controller what else we have this HTTP Sol response to return back the refresh token uh when we are uh signing up so that we don't like some at some application in bad design application you will see that when you sign up uh you your account is created but again you have to go back and sign in again it is a bad experience right so here we are not doing that we are doing the sign up we are returning the access token as well as refresh token and uh what ideally you should do is you should after sign up successful sign up return back to the uh I mean forward the user to the actual homepage okay so this block is basically saying that hey whatever the error that you are finding here in this dto just make a list of it and return back okay with the bad request let's create a method called uh registered user so let's go there create a method called register user I'm just going to copy this whole Stu till exception here and put this thing here okay so what we are doing here is in the registration dto first checking that hey whatever the uh D dto we are sending uh is this user exist if it exist then return back that hey user already exist and and in this user info map but basically you should not I mean convert this dto whatever you receiving from the U uh from the API uh to The Entity object you should use a mapper do the validation check and what not extra varation check if you want to so let's create a package called mappa and in that mapper uh let's call this file name as oops uh where is that okay let me open that did I close it okay it's fine we need to create a user info mapper user input mapper and let me do this and this okay we were at the bottom right at the signup pH so let me copy this user info mapper is basically not doing anything it is uh just converting a D to our entity so here you can do multiple checks if you want to add something remove something uh in the roles you want to add something extra based on the email ID or what not you can do it here so but I will suggest never to convert your dto into DD use some sort of mapper it is for the protection uh it is good for the protection as well I mean it is followed in production envirment as well so let me also add mapper here private final user info mapper uh user info mapper so your mapper is done now in the security config you just need to say that hey if somebody's signing up don't check anything because you will not have either the access token or the username password or anything like that right uh because you're just creating the account only okay in this let's go at the bottom after log out let's put in order of five here uh let keep it five make it six so what we are doing here we are seeing that hey if somebody is doing the sign up don't check anything just permit all the request uh and uh it will be done for all the API request coming in so let's restart the application and finally you will be able to create the new user called sign up so right now let's create this user you will see uh you creating the role of manager right so let me copy this and let's see if you can access it you should not foron uh should be able to access this manager right so you are able to manager and your name is manager one not manager right so and you are doing the sign up in the cookies you will see you have a refresh token using the refresh token you can get the access token right so using the refresh token you can get the new access token I will copy this and again I will try to do p manager I should not let's see the manager okay I'm I'm able to receive welcome message okay let me change it to Z scope read and let's see in the database finally if everything is correct here you will have four user instead of three four user with the role du manager so finally I believe you should uh understand now what uh uh access token refresh token HTTP only cookie jpa and whatnot filters is so if you like this please like share and subscribe it took me more than 15 days to I mean put this in this format so that it is easy to understand and yeah please put it into the comment uh what next tutorial that you want to have so thank you
Info
Channel: atquil
Views: 3,054
Rating: undefined out of 5
Keywords: #SpringSecurity, #JWT, #OAuth2, #JPA, #SecureAuthentication, #UserAuthorization, #HTTPCookie, RefreshToken, AccesToken, oauth2, openssl, httponly refreshtoken, httponly
Id: Wg6qWcDpoZU
Channel Id: undefined
Length: 121min 23sec (7283 seconds)
Published: Sun Jan 28 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.