Spring Security 6 JPA Authentication: A Step-by-Step Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] Welcome to our video on sping security with jpa authentication in this video we will show you how to secure your application effortlessly using Spring Security in combination with jpa first we'll demonstrate how to configure Spring Security with JP authentication you will learn how to define your security settings in a configuration file next we will show you how to create custom user entities and repositories using jpa these entities will represent your applications user and their authentication details you will understand how to map user roles and permission granting or denying access to specific resources within your application then we will guide you through the process of implementing password and coding and authentication we will use use password hashing technique to store your password securely protecting sensitive information from potential breaches by the end of this video you will be well equipped to implement Spring Security with jpa authentication in your own applications you'll have the tool and knowledge to protect your application and Ure that only authorized users can access its resource hope you will enjoy it let's write some code I'll start the project from scratch for creating a new spring board project I will use my favorite online spring initialization tool go to start do spring. iio make sure you have selected Maven project choose latest version of spring at the time of my recording the latest version is 3.1.5 you need to choose jar packaging and make sure to choose Java version 17 in the project metadata give it a group [Music] name give a artifact name spring jpa o name is automatically generated from my artifact name I do not need to change this let's provide a description spring security jpa authentication project it's time to add dependencies first I need to add spring wave I want to expose some end points then I need Spring Security need to add spring data jpa for Java persistence API I will use MySQL for my database so additionally I need MySQL driver now click generate it will download the project in Gip format I have unji and imported the project into my ID I am using the intellig idea ultimate version you can use whatever IDE you are comfortable with now start the project it fails to start let's check the reason open the console fail to configure a data source the URL attribute is not specified and no embedded data source could be configured the primary reason behind the error is that jpa requires a properly configured data source to connect to database if spring cannot find or configure a data source it will throw this error so let's configure our project for database connection I am using myql database for for this project let's connect with my database intellig idea has a built-in tool to communicate with the database this tool is available in this ultimate version if you do not have ultimate version you can use a free tool like MySQL workbench okay let's start with that click on this database icon on the right panel of the IDE or you can open it from view tool windows then database click on this plus icon to add new database connection data source I need my SQL so filter for it click on that if you are using first time you may need to install a database driver for MySQL let's download it by clicking here the download button it has downloaded the driver give it a name I'll will keep with the default one give the host in my case it's Local Host and the default port for MySQL is 3306 give username then password now test the connection make sure you get the message succeeded otherwise review your configuration now everything is okay for me go ahead and click okay and the first thing I do is create database schema right click on this database Source new schema give our schema name spring _ jpa now let's establish a connection between our application and the database that we have created open application. properties from SRC main resources rename it to application. yml using yml file for setting up the properties is just my personal preference you can use your old application. properties file nothing wrong with that it's time to provide our database information in this file so add spring data source URL here we need to provide our database connection URL for MySQL it is jdbc colon MySQL colon dou slash then Local Host this is because I have my database installed in my local server in your case you may need to provide your IP address of your server then colon provide the database server port in my case it is 3306 then slash name of the database scamer next we need to provide our database username my username is root now provide our database password it's time to give the driver class name for MySQL this is com. MySQL do cj. jdbc do driver this driver class is used to establish the connection to database from our spring boot application now we need to provide a couple of other properties like jpa show SQL I want to see my query on my console so make it true this is only for my development purpose usually when I deploy the application to that production server I Mark show SQL as false our database is MySQL next we need to provide a database platform we can give it as database Das platform and the value of our platform is org. hynet do dialect do MySQL 8 dialect you may have question about why we need this dialect hnet dialect specifies the type of database being used allowing hibernate to generate appropriate SQL statement for that specific database in this case hnet will generate SQL query for my mySQL database if we have a Oracle database which has a slightly different query structure we will have to add hynet dialect for that Oracle database that will generate SQL query for the Oracle database okay and then on the next line hiber net insert hbnet dtl O2 the standard hibernate properties values are none validate update create and create drop what it does is that we can tell spring boot what to do with database table when starting our application when we give create drop then spring boot will create the database table when it starts and delete it when stops if we give it a create then it will try to create tables when the starts but will not delete when we stop our service on the other hand in case of update hnet checks the database for details and compare it with the information from our codee it tries to make adjustment to the database structure like adding new columns or table but won't remove anything that used to be there before I'm going to use this update here next I would like to see query formatted for better readability so we need to add properties inside properties hibernate then format SQL and set it true that's all for now take a look at this indentation you have to be careful with this indentation of this jpa should be the same as the indentation of data source take a careful look at overall properties if you feel confused please check the source code from my GitHub or give me a comment below let's start the server and check what happens now the server has been started at port 8080 it also generated a password for loging into our system let's check it in the browser here is our login page the default username is user and the password is the random password that is generated by Spring but we don't want to use those we want our user information to be stored in the database and we will use that information to login the user to the system let's start doing that first let me give you a summary of what we need we will need a security configuration class for configuring our Spring Security to use jpa next we will need entity class I will call them models one is user and another is roles these classes will represent the table in our database for example we'll have user table with couple of columns that will be represented as the user entity similarly the role table will be represented as role entity feeling confused don't worry we will exploit it here hopefully it will make your concept clear next we will need repository classes the repository class is responsible for the communication with the database we will also add a service layer so that we can separate the database logic from our controller the controller will be responsible for handling and processing URLs and they will talk to the service classes and then the service classes will talk to the repository and entity classes to handle database queries now let's start by creating package for our models right click on the project new package give it a name model inside the model package add a new class right click new Java class make sure this class is selected it will be our user class annotate it with at entity to make it entity class give annotation at table inser the parenthesis give the database table name that you want it to be Ma I will give it user this name does not need to be the same as this class name this can be any name like you can give it a name like admin uncore users in that case it will be mapped to admin _ users table in your database I'll go for the user next we need to provide our entity class a primary key to do so give an annotation ID I want to map it to the ID column of my database table so give another annotation at column provide our column name in my case it is ID next declare a field our field type is integer and name is ID let's import the class for ID annotation here are two package available from where we can import The annotation make sure you have selected Jakarta persistence we need to add another annotation to this primary key to let hynet know how to generate the ID this is using add generated value inside parenthesis give it our strategy generation type do identity this strategy relies on the auto increment functionality provide the database to generate unique identifier Valu automatically next we will need a username so column the name of the column is username field TP is string and the field name is also username now we need the password column column name password the field tab string field name is password it's time to give our user a role our users can have multiple roles for instance an admin handles the behind the scene task that keeps the company running smoothly they are also considered as a staff member of the organization so our user will have list of roles let's create our roles class mark it as entity map it with the role table give it the primary key ID the column name is ID the field type is integer and the name is ID add generated value strategy is Generation type. identity next give our rer name column name field type string and the field name is name now back to the user class annotate the rule with one to many annotation we are using one to many relation because our users can have multiple roles we want the rule data to be loaded from the database immediately when the user entity is loaded so use fetch equal fetch type eager now we need to create CER and Gator for both of the class first in the users class inside this class right click generate Gator and seter select all and click okay do the same for R class right click generate Gator and seter select all and click okay now start the server look at the console here is our hnet query hnet has created a table in our database this is the query for the rooll table and this one is for user and finally the mapping table for our user androll let's conect database from my database tool here is my dat database this is my schema let's expand it uh I need to refresh just click here this refresh button to refresh the database now click this Arrow to expand this here it's showing that I have three tables let's check it expanding see we have three tables roll user and user Ro list for roll we have two columns one is ID and another is name and on the other hand for user we have three columns ID password and username similarly this is our mapping table user Ro list it has two column user ID for storing ID of the user and Ro list ID for storing the ID of the role okay back to the ID create a new package Repository for holding repository classes a spring data repository is an interface based definition used for accessing and managing data it provides methods for common data operations such as Reading Writing updating and deleting records these methods are defined in the repository interface and spring data automatically generates the necessary implementation based on the method named and query derivation strategies now let's create a repository for our user right click new Java class make sure this time select this interface name it user repository this repository extends the jpa repository from Spring data then give a angle bracket inside the angle bracket give our domain type that it will manage in this case it is users and next give the data type for our primary key our primary key is ID which is an integer this integer is a primitive data type jpa repository does not accept it rather it requires a rubber class of integer let's provide it also update a data type of ID of our user class update the Sater and Gator method for the idid do the same for the rule class now let's configure our sping security to use our user from the database create a new package name it config inside config create a new class security config annotate it with ADD configuration to mark it as a configuration class inside class we need to create a bin of security filter chain and name it security filter chain it accepts the HTTP security object name it HTTP inside the method provide HTTP dot form login we will use the default login form for now then we need to provide user details service here we need to pass our Custom Service which will implement the sping boots user details service let's create our service create a package service inside create a class user service Market with service annotation this class will Implement user details service from Spring boot this requires a method to be implemented let's implement it load user by user us name this accepts a username as a parameter in the return statement we will give our user F from the database we will query our database to get the user by their username open our user repository class here create a public method of return type user name it find by username this find by is the convention of spring data jpa after find by we need to provide the field Name by which condition we want to query our database in our case we want to query by username we do not have to do anything else spring data jpa is smart enough to create a query on its own to face the data from our user table so in our user service this method needs to return a type of user details so open our user model implements user details from security core user details this needs some method to be implemented let's implement it select all the method and click okay here are our methods first get authorities this method is for getting the list of roles or you can say the authority that the user have we'll get all the roles that the user has and push it into the list of array of dip granted Authority create an array list of dip granted Authority now look through the AR list of our roles I will use for each Loop to do that for the data Tye is RO and the list is RO list inside for Loop here create a new simple granted Authority object simple granted Authority actually the implementation of of the granted Authority interface here pass the rle name as a parameter roll dot get name add this thing to our Authority list and finally return our Authority list here are our remaining methods this one is account non-expired make it true another is account nonlocked this is also true because we are not implementing any lock or unlock functionality of the user right now and is credential nonexpert is also true and finally is enabled make it true as our user will be enabled by default and in this video tutorial I have no intention of disabling the user now to our user service add a private field of type user repository name it Repository mark it as final inject it using the Constructor right click inside this class file generate Constructor select this user repository and click okay in our load user by username method return repository do find by username pass username here now go to our security config class add a private field of type user service name it user service mark it as final inject it with the Constructor generate Constructor select user service click okay now here give our user service as the parameter of user details service finally call build method this throws an exception let's include it to the method signature and return the whole thing run the server in the browser go to Local Host 8080 it's now showing 404 error it's trying to access the root URL but I want it to be protected by default and user needs to login to access this so in our security config after form login method add authorize HTTP request inside parenthesis Lambda expression RQ Arrow req do any request I want all incoming request must be authenticated let's move it to a new line for better readability but there is an exception we want all user can access the login URL so before applying this restriction at dot request matches give our login URL followed by double star and part it all now restart the project check in the browser here is our login form currently our database is empty we don't not have any user and rle saf there so let's add a new user to the database now open the database tool this is the database this is our schema then table then user I need to add a new user in this user table right click this user then edit data let me minimize this tool window it's showing data from our user table currently we have no data here to add new user click on this plus icon this autoincrement ID will be generated by MySQL so I don't not need to provide any data here let's give it a usern name of admin and give password saving this type of raw password straight into the database is dangerous we need to Hash it so that if the database is compromised the hacker will not be able to get actual password we will use bcrypt password hashing technique let's use an online tool to generate bcrypt has value of our password go to bcrypt dash generator. here in the string field provide our password click on encrypt our hash password is generated copy this and paste it in our password column of user table in the database now click in this Arrow here to commit our changes in database a new user has been saved to our database and the generated ID for it is one now it's time to add roll select roll table right click edit data let's minimize it here click on this plus icon as I mentioned before we will have two roles one is admin and another is staff so go for the first one it is admin and the second one click on the plus icon name is Staff commit the changes to persist our role has been saved role for admin is one and staff role is to now let's assign admin rule to our user so again from database tool open user rooll list table right click edit data here click on this plus icon in the user ID column provide the ID of our user the user ID is one for admin rooll the role ID is also one so Ro list ID is one now the changes we have assigned a role to our user let's close those now run the project the project is started open the browser provide username password sign in login failed let's check it from the console this is our query ah this is our error there is no password encoder mapped okay that is because we need to specify a bean of password encoder to let spring know which password encoding technique it needs to follow so in our security config add a new beIN password encoder name it password encoder return new bcrypt password encoder that's it run the server again check the browser refresh provide our username password sign in okay it's successfully signed in but it's showing this 404 error page because we have not configured any endpoint for this root URL so let's do it create a new package controller inside new Java class name it dashboard controller and anate it with rest controller now provide get mapping for root URL give a public method return type A String name it dashboard and return a simple string welcome to dashboard that's it run this project open the browser refresh provide username password sign sign in we have successfully logged in that's why we are able to see this text now come to the authorization part let's assume we have two endpoints one is admin and another is Staff admin endpoint is accessible only by admin user while staff does not have any access to that endpoint and staff where admin and staff both can access that so let's create two endpoint in our controller min miniz the console stopping the server close this project menu for making some room first one G mapping for admin public method return type is string and Method name is admin return a simple text you can view this only if you admin now add another important staff public method with return type of string name it stuff return a simple text now in the security config after this wh listed URL add dot request matchers admin followed by double star has any Authority admin only the admin will be accessed this page again dot request matches staff followed by double star has any Authority admin and staff so what we are doing here is that this admin page will be accessible only to the user who has admin role but for St if the user has role either admin or stuff he will be able to access it and the root URL will be accessible by all now in our database let's add new user for our staff from database tool user right click edit data click on the plus icon add username for staff for password copy the previous one and paste it done commit the data staff user has added and the ID is to so in our Ro user list edit data here is user ID column our newly added users ID is two and for the staff role the ID is two commit the data now let's start the project and see what happens open the browser refresh give our admin user password we have logged in it is our root URL let's try to access admin page it's accessible now access staff this page is also accessible to the admin now log out try to login using staff user password login again the root URL is accessible by all the authenticated user try to access stuff page it's available for staff now let's try to access the admin page this is for 03 error that means staff does not have any permission to access this page and that brings us to the end of this video tutorial I will be returning with another one very soon in the meantime keep learning keep exploring and most importantly never stop happy coding
Info
Channel: Learn With Iftekhar
Views: 2,931
Rating: undefined out of 5
Keywords: spring security, spring boot, spring boot security, spring boot 3, java, spring framework, spring security 6, spring boot 3.0, spring security tutorial, spring security in spring boot, spring, spring data jpa, spring security tutorial for beginners, spring boot microservices, spring security jwt, spring boot tutorial, security, jpa, spring data, mysql, spring boot project, jpa repository, spring security 6 tutorial, authentication spring boot, java tutorial for beginners
Id: jPmkcFjbQCM
Channel Id: undefined
Length: 34min 17sec (2057 seconds)
Published: Fri Nov 17 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.