Spring Boot Security enables role-based authorization by implementing authentication and authorization mechanisms where users are assigned roles (authorities) stored in a database, and access to application resources is controlled based on these roles using Spring Security's API, UserRepository, UserDetailsService, and Thymeleaf security tags.
Spring Boot Security: Role-Based Authorization Tutorial
Added:hi welcome to this video tutorial Spring Bush security or always authorization with minimum income Cotabato net throughout this tutorial you will learn how to secure web pages in a simple application by implementing logon allow and permission assignment for users in other words you learn how to implement robust authorization using spring security api's from existing springboard application let me show you an existing spring Buettner project in spring to suite any if she is a product manager project it allows the user to manage products like vo products great products edit product and delete brother now let me run this remote application to test east near future currently this terminal application is unsecured and we are going to secure it okay the application is up and running in our last test it in a Chrome browser localhost 8080 and I see this is a product manager application developed in the screen put it allows users to manage products like Google products quit new product and attend near it let me create a new product for example Kindle Fire playing Amazon made in USA priced 99 energy in the new product keen Ohio what created here and I can edit change the rise to 100 and made in China safe see it is debated and now I can delete a product I did it in publicity so that's very basic crud features three more application you see this application is unsecure everyone can access is functionalities and now we want to secure this application by adding along with local functions and authorize the users based on their roles we will be using spring security ideas to authorize a users based on these permission details the users having the raw user can be contact list and the users who have zero editor can view create and edit products and you just go have the roll and mid can be crap edit and did it products you know there was the admin can do everything do all the features now in the application the editor can only view create and edit and the role user can view only and here as a technology used in this wing put project screen from book spring boot spring security IP eyes spin data JPA with higher net to access the database for the data access layer Tom leaf for the mutant rest maven for Project Blue Spring would adapt to for automatic restart and a lot whenever we make changes to the code and MySQL JDBC driver so that means in this tutorial we give me man robot is authorized ation using spring security spend it as API we tablet Tom leaf and MySQL database to follow this tutorial make sure that you have the following summer programs install on the computer the Java development kit jdk spin to sweet ide and SQL database server and tools like mysql workbench and here as a step which we will follow great tables and the credit balances configure data sauce cause user and row classes coda is a repository class interface and in demand the user details tunisia TTL service and configure on education and authorization and this is a cost that iran i will explain it to you later very shortly the first step is to create tables in SQL database to store the credentials and authorization information like row names and an assignment for example we create three different users the first user damaged M has a role is a the second user admin has a role madmen and third is a Alex has a role either an editor so as you can see the user can have one or more rows and Rho can be assigned to one of my users so this is a table entity relationships we have we need three different tables to store the credentials and also personalization information the first table is that users table to store the current just like username password and the second table is the row names you see row ID name and because the entity relationship between the user and Row is many to many one user can have one or more rows and a row or can be a side to one of my users so we need to have hmm have an intermediate table users roast here to remove and I want to sorry to implement many too many divisions between the two tables gives us ten rows to a man authorization you know last Christie Street a Boston Massacre will bench you see my ask Claire woman is she database schema we are using walking on East sale newbie now let's quit the first table use us to store the credentials you can see the existing tables product and customer to Stasi information of the application now we need to create three different tables for the authentication and authorization per table and this table name is users first column is problem primary column user on a squaddie digit i integer EK primary key not know and auto increment and the second column is username later tire chair for the fry not know the third column is password watch our 64 because we are going to use bcrypt password encoding for password so the size of this column must be 64 not know and woolen type column in a world woolen here energy and because the MySQL doesn't have a bullet at a time he's converting to converted to a tiny in time here okay click apply to resist you just able to store the credentials username password finished here we go I use a stable wadd credit tier and the second table is tazza row of the row names are permission per table and this table name is rose the first column is a primary key Oh Alice can ID primary key not know what were increment and the second column is name the name of the row or name of the permission no no nothing is no rows table is very simple the black finish and the Terr table is an intermediate able to LeMay and many many one many to many relationship between users and rows table this intermediate evil has only two columns news Nisqually and row on the sky so prison third table save on a missed you just under scroll rows and the first column is even a squaddie at a time into the second column east row the scottie it at ieast in and this has a tooth foreign keys to the either stable Andros table click apply to critics table first apply and click it of Frankie's here and that we great foreign key different key is even a scar FK reference a table is a user steve-o gives us and column is Anna Skye be referenced Columbus honest query and the second now foreign key he's wrong let's go FK reference table is roast yeah hold on the score ID okay and click apply to grid to foreign keys apply finished so we have created three tables gives us rose named user underscore rows to store the Crenshaw's and authorization information now we ingest some data for the roast table first to specify the permission names so the gross yeah and until the first row name is use a second row name is Edmond and the third neuro name east editor click apply bla finished and she ingest Nero table we have three rows user admin and editor you know last great some you just in the users table here and the authorization information in the rows table select rows and we input the data for the users table the first user name is Naimah same password code enable one minute to and second user is admin password named enable on and Theresa Alex password and it's in a world or and because the password must be encrypted in the strong password now is my bcrypt so we need to use to write a small program to encoding robust word into an encoded format so in the project we in Ryan task class T in the test folder here new class a name public earth is password generator exists option to generate the main method finished and because we used bcrypt algorithm for password format encoding password so here we create a new instant habla bcrypt password in CUDA provided my famous QT ABI but you see he has no suggestion proposed us that means we need to declare when this necessary dependencies in the project bomb fire here so i also show you the second steps second step is to declare a necessary dependency for the project to use bring a security ABI is time leaf spindly does API hibernate in this mavens purify here and you can see here we used a spring would stutter data's api here this dependency is required for using spring leaders api with hibernate and spring would start a time lift we Thomas and MySQL connector Java is JDBC driver for MySQL and now unless at Dmanisi force being security I be honest in emergency group ID east of Spring Framework not boot an artifact any East spring dust boot dust starter last security this is a demon see for spring security api's okay safe and you can you can also notice that the spring boot depth 270 is used so when ever I make changes to the code it automatically restart the application now in the password there is a class we create a new instance up bcrypt that's what in coder in cauda equina new will creep password encoder and robust would is core java in coded password is as a result function in coda in comas word and print out the any coded password to standard output let's run this program to obtain the bcrypt for my password core java here so copy and paste into this editor in my scale what when she was what core java and admin user has password in DES copy and paste into this and Alice user has password Alex next copy paste here it is Charlie recommended to use encoded for my password we should not stop mascot in plain text because it is unsecure click apply to curtain g3 tip three you just in users table you see that we have three you just nervous them and minion Alex and now yes I host of other users user number stem has roll user user admin has admin and user Alex has rows user an editor so select roast from the users table user number CMS 91 and the roll user has ID one so you see you on one and you can see in the users table user name is named as his ID 1 and parole user has 91 you know was a and he's ID 2 and row I get to so the data in the users overall - oh he's - - he's a user like hands id3 and row editor row user has 91 and the role it has ID 3 as you can see here 93 is for the ouro editor so you can see is I use a related you know has two different rows for usual Android eater click apply and apply whatever the energy user Eddie Tracy there's something wrong to the table yeah we must remove the primary key hmm let me check and check primary key here for the user and the squatty column means I use a zero stable apply apply hmm we've got an error here Frankie continue the criteria font color least tone tone safe let's check off one key hero his is it is correct you success okay now let's insulator rainfall this gives us a row to hoe say crows and you can see we can already yeah visually yeah so we use a insert statement insert into his rows user Alice quality wholeness call Wendy relative one what is for the username is AB persecutest insert statement you see one rows affected here and for the user admin user ID to row ID to execute and for the user ID three Alex I use ID 3 already one execute and raw I need three execute enough select rows from this table and you see we have information for the authorization here row assignment and next we need to configure data source information to specify the data based collation information so in the project opens our application not profit is fire here and specifies a database URL is a name and password and here you can see the musings database schema Co maybe she's the way schema see sales DB here you know that we use this the spring or the doors API no time late not near just to equal none so upon startup Hamlet we not create the tables and next we need to code domain model classes users and row to map it corresponding tables in the database so create a new Java class here class name least user finished it's best to stop hovering replication because we are going to make a lot of changes to the code when just God has some fused in his ID and string username and password and enabled in a war in general getter and setter matters for this domain model class is a sauce Zen way better and said here and select all to generate greater than Jedi mastered for all the fields generate and reformat the code for me and we had to use some CPA annotations to map list class with the corresponding users table in the database the first annotation needs DT from your APA when the second limitation is table and we specify the table name is you just and for the ID column we need to use the ID annotation to specify that this is a primary column and press specify the column name in the database user underscore ID and because the values for this field is for this column is also generated by the name of database so we need to use them the value annotation since strategy is generation type identity okay that's was a user table and now I scrape the raw grass to map with a rose table here with only two clumps or idea name so create a new Java class sorry class row is only a name of the row promising name Authority name in generated in set of a test cycle generate and format and we use the notation entity in true name equal rows and to map the ID column ID field to the user and a row or a squatty column in the north table ID column named leaf pro on the squatty and generated strategy generation type identity this is very simple for the role class and because it is in submitting the users and the Rostov East many to many many to many so we need to write some a chequered to young man many-to-many relationship in domain model gracias so in this user class tweak it setup rose by with said row rows equal new asset to image many to many relationship when we generate the wet and set from 0 set here then you see and they will use a many-to-many annotation we can trust gate Kaskade type call and first time is yo yo so when the user object is a lot also associated rows will be loaded as well and we need to specify the size table you know a table for this many-to-many relationship the table name is users and the scholars and joint column by column the user underscore ID and inverse is all columns know a column is column or row on this query that's it last was many to many mapping between the user in row we don't need to do mapping in the row crust because we used redirection many to many years so she asian so user object we have a set of rows here and the next step is to could use a mo depository class to take the event is now spring data JP i need to authenticate the user select user by user name so in the project we created me were interfaced sorry need to could interfaced not class the name of the interface is user repository and it's super interface T is yeah the crud repository interface I defy my string security sorry we provide spring data API okay finished and specify the domain type here is the user class and tie-ups ID is a teacher integer is a type of the ID field in the user table it is a class here and in this interface we defy only one method to authenticate a user public user read user by user name then we use an embedded the API query here the query is slow even from the usual way you've got username equal parameter username and in this method we specify the para annotation user name is Marie of variable in-stream user lab and at runtime in the spring data's API we generate code for implementation of this interface so we don't have to write any concrete code justify this interface and swing the JPA we do the rest basically while query and returns the user by user name and to use the spring security api's do we need to remain the user details then user details service interface first last engrams or user details interface to provide user details information to be used by spring security so critters have a class here class name is my user details and is ship interface east user details justify by spring security okay finished and this class wraps and instead of the user to win model past here so we create a private instant film user user here in general contractor using few sources a constructor using fuse and select only the fuser here designer right now we have the constructor here and last you know why is a matter as defined by the user details interface required by spring security password yet the user password user password rather user name user going to user name for this trial method will return to to is the canned and locked rated - sure and this neighbor will return user least enable method and for this method the red authorities we need to provide setup rocks in form of authority so here we get a set up row row from the user object say Rho Plus user red rose and for each role in the set rows we create correction simple granted Authority here you see a question of permission to the user authorities equal neo-realist and here we had a new simple wanted authority to the correction for each row authorities new simple granted autoroute en0 name poki Roni okay and return the correction alterative okay that's it for my user details class sorry here is the robot redneck and the second class implements user details fist has to acquired by screen security to authenticate the user and got a user information based on user name so create a new class here class name is user details so list implementation I about PR instrument first is details this here okay okay and in this class with it over a lot user by user name right and since we are using screen data's API so we in second instant not user repository interface here probably user repository user repository and we use the auto why annotation tool at Spring Framework automatically generate implementation and inject an instant of user repository into this class and in this lot user by user name and litter to be used user repository the user user equal user repository that is a by username username and we check it because I know then with from exception throw new username not reception not user as a quest will return a new instance now my user details wrappings on the user okay so this was a user details with implementation class and finally we configure spin security for the authentication and authorization to connect other piece together okay create a new class first name mr. web security config and this class stand based class web security configure configure a data here okay finish and this year configuration class we must use the annotation configuration from Spring River and to enable spring security we need to use the inhalation enable web security and we need to declare be for the user details mist not like there's a detail detail serviced user details service and in this method we return an instant of the new instant on the user and it yield detail service implementation most we have coded and the second bin is - let's bring know about the Piscotty encoder we want to use green front like the Crypt bus was in Qatar we used equipped because it is recommended by spring security mascotte paint coder and we return a new instance of bcrypt password encoder class and next we need to declare beam for the thou authentication provider to be public endow authentication provider authentication provider and we create a new instance of the authentication provider what provider equal new now authentication provider and we set the user detail service then password in Qatar for this demo authentication provider said password in CUDA must put in Kutta method and said here's a detail service here's a detail service here's a detail service and return object odd provider and we to configure space Cupid configures bringing security ideas for authentication and authorization we need to run couple of matters so sauce overriding women might test yeah choose the to my test configure STD be security and got you with on education manager builder is to my trust okay and in the first configure method we set the authentication provider for this art on tickets and provider education provider method and in the configure within the HTTP security parameter here we'll configure the authentication and authorization for the application HTTP authorized request require that no other users must be authenticated to use the application and you request sorry any request authenticated to users Matt login and we use a before log in form permit oh so everyone can use a login form and we also permit Oh for the logo that's wonderful okay so a lot of code has been noted now let's start our spring replication to see to make sure that nothing wrong okay start our screen put application okay was the application is up and running and seems that no problem but in start-up well access the application and we should see the following form here provided by spring security and try to enter a username and password and we got their bad credentials you know I know in which is you see we credit three users now MSM and minion elects now let me know in with the username best F now missed him password code server here we go I have successfully logged in to the product manager application and you see we need to display the username of the logged in user in the top of the page here so we need to use the term leaf integration with spring security API so we need to declare an additional dimension see in the level right here or time leaf integration with spring security independency rope ID is term leaf not access and if I gotta is term if and asked I just does speak security five safe and now let's edit the home press table application in index dot HTML file here and to use syntax not timely for a string security authorization we need to declare so declare I say my name is placed here X my nest SEC equal HTTPS term leaf not so last term leaf dust I just asked spring secret e5 and for authenticated user we displays a username and logout button so we use a deep section here and use SEC : authorized and the method is authenticated so only authenticated users can see this section and welcome assist their following by the username and to display the user name using Tom if we use the SEC authentication and make whenever username with terminate save the change refreshed last the winner with Miss M Tatiana and she there's a welcome my sister will come username so authentication name I think we need to stop and we start the whole application like authorized is authenticated SEC what education equal named Tammy Tammy nature spring secret if I okay let's check the dependency graph I yeah make sure that terminate I just brings good if I here okay now start the application okay first there's no win away energy this place in the username is name here where they would write we want to make the username in boat so what the spent up here inside meet here you can see welcome them yesterday and we can display the row names of list user you spend time rose and use a comment sake authentication equal principal not authorities and it with this blazer row let me see principal authorities my mistake authentication here energy in this blazer row named after the username here now let's get a lower button button we must leave informed to use HTTP POST request th fraction equal let equal cost and we have no opportunity input type equal submit value no well safe you know she the lower button here you can click here to lower energy you have inside out in our read in sign which user Herman eventually welcome Edmund and the roll name is Ania in log in with a user Alex and you can see this news Ehrlich has two rows to roast editor and user here so far so good right you know last you know authorized users to use specific functions of the application based on this promise in details the user having the raw user can view only the product list and editor can view like create and edit products and admin can be read in head identity products so in the spring the security configuration fine here we need to write some code to authorized users based on URL use a method and matches and specify the URL for example is a admin can delete the products so for this area of the user must have the has authority has Authority and as you can see we have also has a row the difference between has row and has Authority method is that has a row method automatically insert the row underscore prefix to the row name whereas the has Authority method doesn't append graphics so because in the database we have your own name which has a prefaced row so we need to use has authority method and the row name here without the prefix has no authority mm and for edit products only the user has rows and the editor can edit product so we user had any authority method here and with this method we can specify a multiple row names here yep and editor can edit products and the reason I need to use our cut a strictly because in the controller class you see the URL eddie full of ID put and delete follow you by idea product also and you can see in the Edit i've been here so this is a Code to authorize a user based on zeros you see and save the change now just log in again with the user numbers em to quit new product list user can create a new product with user with zero is a but cannot ID you see I want the error message for stbb state at forbidden for three because this user doesn't have permission to edit or delete she no no Ellen left the win with a user Alex who has role editor end user and Alice can create new contact and edit product update this product the price is 199 it is updated and try to get it and you see I want an L here because the user with the role editor doesn't have permission to did it always gives us with row admin can delete the products and we want to customize your arrow piston here for unauthorized error message and do so in this method we caught an exception only access denied test and specify the URL for the access denied - for example for three and we need to map this area with a view name in will terminate in cradle tablet near HTML for three and finished in the title we accessed deny the Majesties sorry you don't have permission you don't have permission to access just press you and in the controller class you know create a method to return you name for last we are in wet nappy for three public tree here all three and just a returned of unit for three that's it say for the changes and unless the log in the rain with the user Alex likes energy [Music] here I'll delete here which I use Alex who doesn't have a missing admin what error sorry you don't have permission to access this paste this user can still use this can still view products and create new product for example kidney product went for friend see omni million china 14 and you see new product here and edit with he tries to 13 my safe she completed but cannot delete you don't have permission to access this space now we want that the users can see all these action that they have permission to do so just like user can see only the hi bring to any Nazis did it heavily and I use a nama stamp we see only the product list and creat new product and this is a user or user what sees actions and it on delete and we need to update the term leaf view here we see for the actions column table had a connection yeah and to authorize the user you can use tablet security is intact except on to rise equal yeah use a method passed any authority same in Java code and we specify one or more role names yeah because the user and madman and editor can see the action column so we call this method has any authority with row name's Edmund and editor and scroll down for the table data here as a detailing here hello you also need to use a slick authorized pad that has any authority and row names came in editor and because always the admin user can delete product so here in the high bring here we can use some insecurity that authorized here's Authority and this time we use a has author limited that takes only one drone a row admin that's it energy East username is damn doesn't see links to edit on the lip product Cory's are going to clean your product and promised and then West Aloha and site which I user admin you see the user admin can quit Nevada and it ended even normally I try to delete a product here you see Nova and let's try to now this time we never use Alex who has a rose user an editor and OC exists user can see always a link to edit the product here so far so good right so far you have learned how to secure web pages and implement robust authorization for the application based on Spring Framework using spring security api's with swindlers API I met and masked clear I hope you found this tutorial helpful please click subscribe like comment and share this video I am not only from Cordova Lynette
Up Next

OAuth vs SAML vs OpenID Connect: Protocols Compared for Developers
@lascon512
37.4K views•2017-11-27

BitTorrent Protocol Explained: Piece Selection & Peer Choking
@StevenGordonAU
481 views•2013-02-22

HTTP Requests Explained: GET, POST, PUT, DELETE
@codecademy
103.1K views•2021-10-07

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science




![Spring Boot Tutorial for Beginners [2025]](https://i.ytimg.com/vi_webp/gJrjgg1KVL4/maxresdefault.webp)















![Spring Boot 3.0 Security | Authentication and Authorization | [New Changes] | javaTechie](https://i.ytimg.com/vi/R76S0tfv36w/maxresdefault.jpg)











![Spring Security - Аутентификация, Авторизация, oAuth, и все остальное - [СЛИВ]](https://i.ytimg.com/vi/wcbqwYFfG70/hqdefault.jpg)



