[Spring Security] Mastering JPA based API security, for Authentication & Authorization

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Namaste everyone welcome to the another tutorial of Spring Security so in this video we will understand how we can Implement Spring Security using the jpa so let's start the first step is to create the project so let's open our browser let's go to Spring initializer let's create a project let's type at Quil let's write uh our jpa as a artifact name let's write a Spring Security implementation using jpa let's SK Java 21 uh spring boot 3.2.1 which is the latest right now let's add some dependency let's add longbo to remove wet plate spring web for the API uh jpa for orm mapping let's also add our uh S2 for our database what else we need uh yeah we also need a Spring Security right the hero of our show let's generate it okay let's save it in so you have to unzip the file so you will get a GPA folder itself now use this GPA into our Intel J right so where is it in desktop jpa let's open this thing now it has opened it will take some time to load uh everything let's pause for that so everything has been loaded if you will start the application you will see that there is a error let's Rectify this error as we did earlier go to Project structure change this SDK to the uh 21 if you don't have Java if you're not seeing this eror it's fine if you if you're seeing this kind of err it means that your SDK has not been configured correctly so if you will see now you are seeing the autogenerated security password right so our application is working fine now let's do all the setup that is required the first thing is to um make the database right so let's make the database uh let's go to main resources and application properties let's change it to yaml file IM IML okay there is a DOT there okay let's open this file let's add first thing here that uh I want to see the S2 console right so spring uh H2 console enabled so this thing is here H2 cons enabled true right what else we need let's create a data source uh let's use the URL uh let's have jdpc database DBC type of database of H2 and let's have the name of at Quil DB Also let's have the username uh essay uh let's have have the password nothing and let's have the driver class name uh which should be or H2 driver okay it's fine now let's also for the orm mapping that we are using jpa right so let's uh configure that also ddl Alo create drop so it says that like Hey whenever this application starts let's delete everything and create uh a new okay now let's also add database platform and we have hibernate right H so now everything looks correct now I also want to add U show SQL to true so that like whenever there is uh any changes in our database it it reflects so till now everything is fine right now let's add user to this let's go to Java let's create a uh entity called user entity uh oops sorry let's create a package called entity let's create a file got user entity so for logging whatever you required you will keep it here let's say that like hey it's NT let's give a table name uh name users if you not giving this by default it will take this as a table name okay so let's create a data for Getters and sets and let's also add a no con Constructor now let's add uh a ID for this table right so long ID let's give it as the ID also we want to generate it automatically uh also let's add a private string username you can give email whatever you want to so I'm just writing username here private string password also write uh private private string roles so it can be multiple roles right so there can be a user uh there can be role of admin there can be role of manager these roles can exist okay and one person can have all these roles or some of them right okay now let's create the repo as well repo now let's Java class user repo so it is not a class it is what it is a interface interface which extends jpa repository extends jpa repository of type what of type user entity user entity and which has long as ID right so now let's also Ed it with repository so that it knows that like it is here let's remove this thing uh because it is error right user entity okay now we have user entity and user AO let's add the user to this using what using command line Runner so what Comm does is before starting the application it executes whatever we give it in this right so let's add the value here so create a bin command line Runner command line command line Runner let's where we need to add the value in the user repo right so let's take this parameter us a reper let's return what let's return ARS so what we need to do here is we just need to create a user entity user suppose we I'm just creating a manager as a user right and so new user entity let's give let's give manager. set username manager manager. set password let's give him password also manager. set rules let's give rules rules manager let's also create one admin let's create this thing as a admin admin and let's copy this admin admin admin username is admin and he has a role of manager as well as admin so it is Rule not rules sorry okay now we have everything here okay now let's add this thing into our user reper so user reper do save all list of list list of what list of manager as well as admin so we are going to add these two into our DB now I think everything should look fine once we restart the application let's see that like if we are able to see any inserts there so we are doing the inserts but can we see the S2 console let's see S2 console uh let's give uh uh user and the default password which is there uh you can see where is the default password Here is the default password okay okay let's connect uh you are not able to see right okay so let's configure uh something so that we will be able to see our uh S2 console right so for that configuration we need to go to our again security config and in the security config we will have to uh configure so that to enable whatever the uh things uh which is coming in the uh sls2 console it should be displayed so let's go there okay let's create a uh new package config let's create a file called security config let's say that like hey whatever the HTTP request that we are going to send uh we will be configuring it here let's uh configuration not cross origin configuration okay now let's start the configuration so let's create a bean security filter chain okay security filter chain security filter chain and let's secure our HTTP endpoint which throws some exception if we are not going to write that then uh it will give error when we are writing like configuring our HTTP okay so return HTTP security let's authorize request let's configure now and we will say that Hey whenever you see uh whenever you see any kind of request match that is and path request match whenever you see uh any request starting with uh suppose S2 console S2 console don't do anything and permit it all permit all but but but but whenever you see any other request just authenticate okay so now we have we have already set for the authentication one more thing that we need to do is csrf we need to disable the csrf for our S2 console let's do that csrf csrf because it affects our application right sometimes it happens so csrf do ignore ignore request matcher same thing and paath request matcher do an and matcher what we need to disable it for console right we need to disable it for H2 console now CSR up is also done one more thing we need to do we need to because the database tables and all it comes under the frame so we need to disable that also the Securities from there also so headers generally this thing you will not write in our FR because there we will be having we will be connecting with the post not with the S2 right so so let's uh yeah let's headers let's add headers headers start frame what is wrong okay h e a d headers come on why why why headers come on dots frame option uh with defaults with defaults let's import the static one okay uh customizer with defaults let's disable it disable it and last of the all if form login is available uh if form login is available then use that otherwise use HTTP login HTTP basic with defaults and let's build our security one more thing is there if you will see um the password that we are adding uh like in our database it is not encrypted okay let's first try this let's restart this application okay no error let's open let's refresh it let's connect you are able to see the tables right but if you will see the passwords are not encrypted let's encrypt our password user entity let's go to our security config let's say that like hey uh password encoder password password encoder let's Crypt our password with bcrypt vry password encoder now let's use that in our when we are encoding the password so let's use that bin password incoder password incoder let's use that here password encoder do encode okay now it has been encoded let's copy it paste it here let's restart the application now if you will see the password will be encoded here let's connect now select user the passwords are encoded okay now let's create some apis so now go to the controller package controller let's write a user controller user controller let's say that hey is uh rest controller let's do a request mapping for or anything coming like a API now let's create some apis okay so the first API which we are going to create can be accessed by anyone okay so let's create an API which is going to be anyone can access it so public response entity and let's put question mark uh it says that like U any kind of response is fine get test API let's do it the return type for this response entity do okay uh okay everything is fine we will just say that anyone can can access me okay so let's we have this API let's also add few more apis which will be restricted so which will be restricted to whom which will be restricted to these users right role of manager and role of admin for that one thing you need to do is you need to also add enable method security so what it means that like uh even though the complete application is being secured by this we also want method level security that we are going to do it here so let's add something which can be access only by manager and this can only be accessed by ad okay and how we will do that we will just add a [Music] pre-authorized pre-authorized value what it says that like hey whatever whenever this API request comes in just check if it has this rule or not has rule has rule what uh rule of rule of manager rule of manager so if it has rule of manager it's fine get this API 1 let's make it one let's make it two let's make it three okay so let's copy this thing paste it here say is that like hey if it has uh has if it has role of manager or if it has role of rule of AD then what you can do is then you can access both of them okay so okay now let's restarted let's see let's go and Local Host 8080 and let's API and we have any anyone let's see uh user and see we have not configured uh till now right we just checking for the apis we are not configured this rules now we have not added these rules to be secured right to be act as a username password so we are just checking that like these apis are secured or not so let's see so user and the password is okay it's saying back credentials encoded passord okay so actually we have already uh encrypted the password right in here if you will see we have already encrypted the password so now it is not able to decrypt it because we have we don't have like the encryption value for this available right so let's let's do one thing let's do all the configuration itself then we will check for the application security okay so for adding that let's go to the conf config let's add a user config user config in this user uh config we can uh change it to users okay user config is also fine let's Implement a user detail okay so what it says that like hey you need to implement some of the methods let's Implement these methods okay now let's see what user details does it has basically username and password which we which which generally by default you're going to use and it also has a collector which is having the roles right get author means it has rules so we will be using our user entity entity these three things to map it with our these three things which is by default which is there okay so where we were in the user config right so let's add now let's add first thing is private final from where we will getting the information we will getting the information from user entity the another thing that we we could have done is basically here itself if we could have just uh added user details but we should not do that it will clutter everything right so that's why I'm doing it here it is much more cleaner way to do that do that thing uh let's add a required argument Constructor argument Constructor otherwise we have to Auto it here as well as create a Constructor so it's fine now let's add the username uh first let's see what the username is return return user entity user entity to get username so it will be our username same thing with the password so let's write user entity. getet get password so we have username and password right and now we have the rolls in the form of a string with commas right so let's add that thing here we will say that we need to just stream the user entity. get roles whatever the rules that we are going to have it here we will just split it split it based on what split it based on comma so once you split it it will be converted into the form of aray right let's split it and make it in the form of arrays you also have to tell them that like uh once you have a splitted right once you have already splitted this value let's me configure this thing and you have this everything in the form of array right then you need to just map it with what with simple granted Authority where is that simple granted Authority and now when you will create this value it's now it will be represented as in the form of user details now you need to just make it to list what it is doing is uh whatever the rules that you are giving here in the form of a string right it is converting in the form of arrays now it is in the form of arrays and we are saying that it is in the form of granted Authority right everything is in the form of granted Authority and we are just creating a rest now our string list becomes a collection of granted Authority right everything is straightforward here right so once you are done with this you need also have to add a method method to what to map the values which are coming from the back end sorry which is coming from the front end to this right so let's do one more configuration this configuration will be J jpa details config and why we are doing this is so that like we have separation of Consul user details service so once you have this let's see which method it is telling it is telling that see load user by username so we are getting the username okay and we are loading it to our user config here let's see how we are doing that let's first add it here simply uh user repo because we need it here right so private Finance user repo user reper let's add a required argument Constructor now in this we just need to verify that user exist or not in our repo so find by ID no we just need to create a method find by username right find by user username and we will pass it the username here so let's create this method in our to user reper so it it is not user details it is basically optional right optional of user entity so if you find it it's fine so let's go down here find it by [Music] username and if it is there then what you need to do map it with what map it with users that we just created right uh user config user config and we need to map it with that and if we don't have any value right or else so if we don't have the value then what we need to do we need to just see that like hey user does not exist so new user not found exception user username does not exist let's make it user this does not exist so here what we are doing is we are finding the user and we are saying that hey um if whatever the user is there if if it is present there then go and map it to user config where we will get uh a particular uh uh I mean user details in the form of uh whatever is required for the Spring Security in username password and will the granted Authority for the same so once you have we have everything let's go to the uh security config so in the security config you just need to add it where is the security config here in the security config you just need to add that file private final jpa user details config user details config so let's also add here required argument Constructor and now we are going to use the this user details config instead of default one in here so how we will add that we will simply say after this that hey we are going to use user Detail Service for our uh security purpose okay I mean security purpose in the sense that like uh change the name JP user detail config let's for our login uh config jpa user details config right here jpa user detail config why this thing is Swing could not Auto the bean uh could not autoare the bean why okay so let's go there okay we have not okay so let's PL this okay so basically it is a method right which is uh uh I mean business logic which is saying that like hey get the user details and map it to the granted Authority and all and return it back right so we are forgetting that so once we restart now I think every should thing should be working fine okay now you you don't see this thing right like uh the default password which was coming Let's test it out let's refresh everything uh uh let's see if data exist still exist in the back end or not connect uh let's see user Run Okay manager and this thing is there and it has having the admin role let's sign in using let's which API you want to go let's go to the manager so let's go to the manager for that let's log in like admin okay user account is locked uh let's manager password user account is logged okay so why this thing is getting logged uh let's see okay so I think I know the reason let's go to about this let's go to our uh user config okay so yeah here there we just need to make it true because we are saying that like hey is it expired true is account non logged true is credentials non expired true and these things you need to configure when we are doing some advanced level of uh configuration so let's restart this and hopefully everything should work let's restart now let's try with the admin and password okay so let's try again uh with what manager API let's try with uh [Music] admin password okay so we are not able to access using this let's check with the admin and um we are not able to access this API also oh sorry we need to access using the API SL manager right okay why this thing message this message is there uh let's check our controller okay message are same so let's change to principal principal this is to check that like hey who is like logging in so I am M manager API is accessed by let's get principal do get name so who is login in you have this information okay let's copy this paste it here as well admin API admin API is accessed by this let's put here principal principal principal principal. getet name okay so let's restart so what we are doing basically is like this manager API right it is um it is going to be accessed by only by the manager and this admin API is going to be accessed by manager as well as uh admin okay so okay so let me change that I think it is better if we copy and yeah this thing should be there right and this thing should be here it makes more sense right so manager and admin can access manager API and just admin can access admin API let's restart it again so okay everything is done let's restart let's log in as admin okay let's I'm not able to access manager API I'm not able to access manager API why uh let's see if I'm able to access admin API admin and what's the problem here has okay it is not has roles has any role has any role sorry let's restart okay now again let's log in from the admin password so admin I can access let's see if I can access manager manager manager I can access now let's log out using the simple log this is the inbuilt feature right uh this is the inbuilt feature given the spring security so let's login as manager password let's login let's go to API SL admin I'm not able to access it right okay so let's write manager so I'm able to access it so there it is there is the simplest way uh simplest way and actually you can use most of them in prodad as well uh for configuring your Spring Security and all one more thing you can do is you can segregate both of them you can segregate these security into two parts uh let's do it itself so let's let's segregate these two into two parts so that like you can have multiple configuration for the security filter chain okay so in this way it it will be helpful for you in future uh so let's comment it let me comment it out uh let's do it now itself let's okay uncommented I will just copy this thing and put it here and here I will just write H2 consoles if you could CH H2 console security chain and here I will write API security filter chain okay so in this you just need to say that like hey whatever the request it is coming uh let's see that like if it matches our pattern or not so and path request match let's see that like uh it matches the pattern of S2 console or not if it match is the pattern of S2 console then instead of doing all this right instead of doing this just remove this part just remove this part then you don't need this you don't need this then just permit everything and yeah you just need to don't you don't need any kind of uh I mean authorization right so header with form login basic login it is also not required okay now we will see that the order of creation of this p is uh it is already been right in the order of creation of this p is first so while creating the pin it will run this thing as first one first priority let's give this thing for the priy number two now we we are seeing here that like he as we are seeing here right like whenever it starts with H2 console here we are saying that whenever it starts with anything called the API let's come here or we don't even need it here because everything else we want to be secured right so let's put it here let's remove this and let's remove that we want it to be secured using this csrf we don't need you we don't need you we need form lugin right with defaults so now even if we will start you will see that application should work okay now let's go there let's refresh it admin password okay manager API is accessed so everything is working and why I did like this is basically uh I mean uh I mean for the future purpose whenever we have the multiple configuration where we are doing like suppose for the starting with the API we want some at one place we want OCTA suppose some API starting with uh like uh AWS we want some something different uh to be authorized with so we can do in this way okay so thank you guys I hope you like this video I know my videos a little bit longer than usual but I try to explain most of the concepts here so yeah please like share and subscribe bye
Info
Channel: atquil
Views: 394
Rating: undefined out of 5
Keywords: spring security, JPA, HIBERNATE, JAVA21, USERDETAILSSERVICE, ROLEBASEDACCESS, H2DATABASE
Id: XK6QcHSQyJU
Channel Id: undefined
Length: 40min 39sec (2439 seconds)
Published: Sat Dec 23 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.