"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : Spring Boot Security Date : 02/08/2025 (Session - 96) _____________________________________________________________________________________________________________________________ Spring Security/Spring Boot Security ==================================== * Security is the one of important aspect of Software Application development. * Generally in the Application development we do have some secure Resources and inorder to access such resources we required to define Authentication and Authorization concepts * Authentication is used to prove your identity such as username & Password,BioMetric Thumb print etc.,If Username & Password is valid then we can say Login Success otherwise Authentication Failure as 401 Response code. * Authorization is process of checking Access Permissions of an authenticated user on differnt resources of the Project and generally roles are nothing but designations given to users....based on roles of the users the access permissions,on different resources will be decided. * Generally If Authorization fails then will return response as "Authorization Fails(403)". Example ======= * If we Considered the Banking Application generally we have several kind of peoples and these people are associated with some roles and each role will have set of permissions. Bank Clerk Employees >>>>>>>>> Clerk Role Bank Cashier Employees >>>>>>>>> Cashier Role Bank Operation Manager Employees >>>>>>>> Operations Role Bank Manager >>>>>>>>>>>>>>>>> Manager Role * As per our scenerio clerk will have very limited access of banking Application and cashier also have limited permission todo cash activites only and where operations manager will have some operation acivities on Banking Application and manager having full of permissions on Banking Application. * One Important point always Authorization will perform after the authentication only, Please go through paint screenshot Diagram ======== (Prove Your Identity) (Checking Access permissions on resources based on the roles) End User sends Request >>>>>>>>>>>>>> Authentication >>>>>>>>>>>>>>>>> Authorization>>>>>>>>>>>>>>>>>>>>>> Access Rest API NOTE ==== * If authentication fails will return 401 error and if authorization fails will return 403 error. * Generally Authentication will performed by "Authentication Manager" and where as Authorization will performed by "Authorization Manager". * Authentication Manager & Authorization Manager will always gets the Information from Authentication Information Provider which contains the User Information. * Basically Authentication Information Provider collects the user information from various Sources i.e., 1) Properties file 2) XML File 3) JSON File 4) In-Memory Database. 5) Database Softwares. * Earlier Implementing the security in Applciation will have typical task and developer also need to focus more on it but spring framework is simplied the security concepts by using Spring Security Module. * Now days Spring Boot Makes very simple we know that below things Spring Web MVC >>>>>>>>>>>>> Spring Boot Web MVC Spring Security >>>>>>>>>>>>> Spring Boot Security * Implementing the Spring Boot Security Will be easy because of Spring beans objects are coming through Auto COnfiguration and completely avoided the xml configurations. Steps for Enabling the Spring Boot Security for Spring Boot Application ======================================================================= 1) Create the spring boot application using below starters * Spring Web Starter * Spring security Starter 2) Create one Sample Rest Controller Class in the Project with below code WelcomeController.java ====================== package com.ashokit.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class WelcomeController { @GetMapping("/welcome") public ResponseEntity getWelcomePage(){ return new ResponseEntity("Welcome To Ashok IT For Spring Security.....",HttpStatus.OK); } } 3) Open the application.properties and change port no :9878 4) Open the Spring Boot Main Class and Run as Spring Boot Application Testing Application =================== 1) Open the Browser and hit the below request http://localhost:9878/welcome It will route to following url for getting login page:http://locahost:9878/login 2) Input the username as "user" and password we need to get from Application console and provide as input and click on Login button and verify you are getting response or not... 3) When we add spring security dependency by default will get "Http Basic Authentication". Providing Own Username and Password For Spring Boot Application =============================================================== 1) open the application.properties file and provide the below username and password server.port=9879 #spring security configuration spring.security.user.name=mahesh spring.security.user.password=mahesh@123 2) Run the Spring Boot Main Class and provide input of username and password supplied in above properties file. 3) Verify our API is able to access or not. *************************Security WorkFlow************************* * As we know that Authentication of an application will be performed by Authentication Manager. * Authentication Manager always collects the users information from various data sources 1) Using Default user account provided by spring boot security >>>>>> Only Development Purpose 2) Configuring the Spring security username & password in properties file >>>>>>> Only these User can Access the Resources * This Approach is also recommended for Development purpose. 3) Collecting the Several Users Information through "InMemory Authentication" During the Spring boot Application startup will be creating set of hard coded users (or) Hard Coded Users with Roles to provide access for Resources. * This Approach is also not recommended because there might be chance of creating new user (or) modifying role of an existing user this will leads code change. 4) Collecting Users Information through "Jdbc Authentication" means we are storing some users information in Oracle Database or MySQL Database inorder to Perform Authentication * Inorder to add our custom logic related to Authentication & Authorization we need to create security Configuration class in our spring boot Applciation 1) By creating Configuration Class by simply extending WebSecurityConfigurerAdapter. 2) We have one overload method in WebSecurityConfigurerAdapter class i.e.,configure() and we need to override two configure methods into our class protected void configure(AuthenticationManagerBuilder auth) ***Providing users Information and performing either InMemoryAuthentication (or) JdbcAuthentication. protected void configure(HttpSecurity http) **** Will be configuring which API to be secure and which API are not to be Secure. * In the recent Version of SpringBoot 2.7 WebSecurityConfigurerAdapter got Deprecated for replacement for this class to provide authentication and authroization through "SecurityFilterChain" Bean Definition. * Make sure Inorder to work with WebSecurityConfigurerAdapter our spring boot version is < 2.7 Authorization levels ==================== 1) permitAll() >>>>>>>>>>>>>>>>>>>>>> No Authentication + No Authorization(No Role Checking) Example: Home page of an Application,Contact us Page of an Application 2) authenticated() >>>>>>>>>>>>>>>>>>> Only Authentication on the given request URL Resource and No Authorization(No Role Checking) Example: Dashboard page of Application etc., 3) hasARole() >>>>>>>>>>>>>>>>>>>>> Authentication + Authorization(Role Checking) Example : Upload Notes option 4) hasAnyRole() >>>>>>>>>>>>>>>>>>> Authentication + Authorization(Any one Role should be there for user in the list of given roles) Example: tranfer Money,Changing Password Example ======= /home,/contactUs >>>>>>>>>>>>>>>>>> permitAll() /dashboard >>>>>>>>>>>>>>>>>> authenticated(); /rewards,/transfer >>>>>>>>>>>>>>>>>> hasRole() "CUSTOMER" /depoist >>>>>>>>>>>>>>>>>> hasAnyRole() "MANAGER","CASHIER" In-Memory Authentication Application ==================================== users.ddl ========= create table users(username varchar(50) not null primary key,password varchar(500) not null,enabled boolean not null); create table authorities (username varchar(50) not null,authority varchar(50) not null,constraint fk_authorities_users foreign key(username) references users(username)); create unique index ix_auth_username on authorities(username,authority); insert into users values('Mahesh','$2a$10$fL5.FByYA0RSox77JIccP.nnL0aFt7qagdftU2tlUDLAMHL8AE1Ba',true); insert into users values('Suresh','$2a$10$aL0.eONRAa109vPTMaD0SODR2QjukIjM4wzXbW9Y39RwxKOJPd4Ey',true); insert into users values('Ashok','$2a$10$UkcZ4bm.iz6/eXy6hswhwudbv2TRylytB69r1Tcm.v4wNBf132Duu',true); insert into users values('Ramesh','$2a$10$vwir.vWjBr4Y3EQlhwghJeVP2xj8zg9yllQwCohfZGguCy78Tkbti',true); insert into authorities values('Mahesh', 'ROLE_ADMIN'); insert into authorities values('Mahesh','ROLE_MANAGER'); insert into authorities values('Suresh','ROLE_CUSTOMER'); insert into authorities values('Ashok','ROLE_CUSTOMER'); insert into authorities values('Ashok','ROLE_CLERK'); insert into authorities values('Ashok','ROLE_CASHIER'); select * from users; select * from authorities; application_users & application_roles custom tables =================================================== create table application_users( username varchar(100) primary key, pwd varchar(100), user_status bigint, created_date date ); -- creating roles for users in the application create table application_roles( role_name varchar(20), username varchar(100), created_date date, constraint username_fk foreign key(username) references application_users(username) ); insert into application_users values('Mahesh','$2a$10$fL5.FByYA0RSox77JIccP.nnL0aFt7qagdftU2tlUDLAMHL8AE1Ba',1,sysdate()); insert into application_users values('Suresh','$2a$10$aL0.eONRAa109vPTMaD0SODR2QjukIjM4wzXbW9Y39RwxKOJPd4Ey',1,sysdate()); insert into application_users values('Ashok','$2a$10$UkcZ4bm.iz6/eXy6hswhwudbv2TRylytB69r1Tcm.v4wNBf132Duu',1,sysdate()); insert into application_users values('Ramesh','$2a$10$vwir.vWjBr4Y3EQlhwghJeVP2xj8zg9yllQwCohfZGguCy78Tkbti',1,sysdate()); insert into application_roles values('ADMIN','Mahesh', sysdate()); insert into application_roles values('MANAGER','Mahesh', sysdate()); insert into application_roles values('CUSTOMER','Suresh', sysdate()); insert into application_roles values('CUSTOMER','Ashok', sysdate()); insert into application_roles values('CLERK','Ashok', sysdate()); select * from application_users; select * from application_roles; drop table application_users;