Spring+Security+Masterclass+Slides
Spring+Security+Masterclass+Slides
com
3. Intellectual Property
All course materials are protected by copyright laws and are the intellectual property of Faisal Memon and EmbarkX. Unauthorized use,
reproduction, or distribution of these materials is strictly prohibited.
4. Reporting Violations
If you become aware of any unauthorized sharing or distribution of course materials, please report it immediately to
[[email protected]].
5. Legal Action
We reserve the right to take legal action against individuals or entities found to be violating this usage policy.
Thank you for respecting these guidelines and helping us maintain the integrity of our course materials.
Contact Information
[email protected]
www.embarkx.com
© Faisal Memon | EmbarkX.com
Spring Security
Password Storage
→ Declarative Security
→ Integration Capabilities
© Faisal Memon | EmbarkX.com
Thank you
© Faisal Memon | EmbarkX.com
PRINCIPAL AND
AUTHENTICATION OBJECT
Principal
Principal represents the currently logged-in user. Your user details
(like your username or email) become your Principal
© Faisal Memon | EmbarkX.com
Authentication Object
Authentication Object is a more comprehensive representation of
the user's authentication information
© Faisal Memon | EmbarkX.com
Principal: john_doe
→ Who you are and
Authorities: ROLE_ADMIN what you can do
Dispatcher
CLIENT Controller
Servlet
Filter Chain
Dispatcher
CLIENT Controller
Servlet
Filter Chain
Filter
Filter Chain
© Faisal Memon | EmbarkX.com
Filter
→ Filters are components that can
intercept and modify incoming requests
and outgoing responses in a web
application.
Filter Chain
© Faisal Memon | EmbarkX.com
→ This process continues until the request reaches the final resource
→ The response generated by the resource then travels back through the chain,
allowing each filter to perform any necessary post-processing.
© Faisal Memon | EmbarkX.com
Summary
→ Filters are components that can intercept and modify requests and responses.
→ Filter Chains are sequences of filters through which requests and responses
pass.
→ In Spring Security, filters are used for authentication, authorization, and other
security tasks, arranged in a chain managed by the framework.
© Faisal Memon | EmbarkX.com
Why Filters?
→ Cross-Cutting Concerns
→ Separation of Concerns
© Faisal Memon | EmbarkX.com
Thank you
© Faisal Memon | EmbarkX.com
Key Filters
SecurityContextPersistenceFilter
Manages the SecurityContext for each request.
Class: org.springframework.security.web.context.SecurityContextPersistenceFilter
WebAsyncManagerIntegrationFilter
Integrates the SecurityContext with Spring's WebAsyncManager for
asynchronous web requests.
Class: org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
© Faisal Memon | EmbarkX.com
Key Filters
HeaderWriterFilter
Adds security-related HTTP headers to the response, such as
X-Content-Type-Options, X-Frame-Options, and X-XSS-Protection.
Class: org.springframework.security.web.header.HeaderWriterFilter
CorsFilter
Handles Cross-Origin Resource Sharing (CORS) by allowing or denying requests
from different origins based on configured policies.
Class: org.springframework.web.filter.CorsFilter
© Faisal Memon | EmbarkX.com
Key Filters
CsrfFilter
Enforces Cross-Site Request Forgery (CSRF) protection by generating and
validating CSRF tokens for each request.
Class: org.springframework.security.web.csrf.CsrfFilter
LogoutFilter
Manages the logout process by invalidating the session, clearing cookies, and
redirecting the user to a configured logout success URL.
Class: org.springframework.security.web.authentication.logout.LogoutFilter
© Faisal Memon | EmbarkX.com
Key Filters
UsernamePasswordAuthenticationFilter
Processes authentication requests for username and password credentials. It
handles the form-based login process.
Class: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
DefaultLoginPageGeneratingFilter
Generates a default login page if no custom login page is provided.
Class: org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
© Faisal Memon | EmbarkX.com
Key Filters
DefaultLogoutPageGeneratingFilter
Generates a default logout page if no custom logout page is provided.
Class: org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter
BasicAuthenticationFilter
Handles HTTP Basic authentication by extracting credentials from the
Authorization header and passing them to the authentication manager.
Class: org.springframework.security.web.authentication.www.BasicAuthenticationFilter
© Faisal Memon | EmbarkX.com
Key Filters
RequestCacheAwareFilter
Ensures that the original requested URL is cached during authentication, so that
the user can be redirected to it after successful authentication.
Class: org.springframework.security.web.savedrequest.RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
Wraps the request to provide security-related methods (e.g., isUserInRole and
getRemoteUser) that interact with the SecurityContext.
Class: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
© Faisal Memon | EmbarkX.com
Key Filters
AnonymousAuthenticationFilter
Provides anonymous authentication for users who are not authenticated. This is
useful to apply security constraints even to unauthenticated users.
Class: org.springframework.security.web.authentication.AnonymousAuthenticationFilter
ExceptionTranslationFilter
Translates authentication and access-related exceptions into appropriate HTTP
responses, such as redirecting to the login page or sending a 403 Forbidden
status.
Class: org.springframework.security.web.access.ExceptionTranslationFilter
© Faisal Memon | EmbarkX.com
Key Filters
FilterSecurityInterceptor
Enforces security policies (authorization checks) on secured HTTP requests. It
makes final access control decisions based on the configured security metadata
and the current Authentication.
Class: org.springframework.security.web.access.intercept.FilterSecurityInterceptor
© Faisal Memon | EmbarkX.com
→ Problem-Solving Skills
Thank you
© Faisal Memon | EmbarkX.com
Basic Authentication
Basic Authentication
→ Basic Authentication is one of the simplest forms of authentication supported
by Spring Security
→ It involves sending the username and password with each HTTP request in the
Authorization header.
→ The credentials are encoded using Base64 and sent over the network. Spring
Security then decodes and validates these credentials.
© Faisal Memon | EmbarkX.com
Authorization Header
© Faisal Memon | EmbarkX.com
Structuring Thoughts
Authentication Providers
Key Responsibilities
→ Authenticate the User
Importance
→ Flexibility
→ Separation of Concerns
→ Extensibility
→ Security
© Faisal Memon | EmbarkX.com
Thank you
© Faisal Memon | EmbarkX.com
Authentication Providers
Authentication Providers
→ DaoAuthenticationProvider
→ InMemoryAuthenticationProvider
→ LdapAuthenticationProvider
→ ActiveDirectoryLdapAuthenticationProvider
© Faisal Memon | EmbarkX.com
Authentication Providers
→ PreAuthenticatedAuthenticationProvider
→ OAuth2AuthenticationProvider
© Faisal Memon | EmbarkX.com
In Memory Authentication
In-Memory Authentication is
storing and managing user
credentials directly within the
application's memory
© Faisal Memon | EmbarkX.com
matches()
PasswordEncoder
Authentication Provider
[DaoAuthenticationProvider] loadByUsername()
UserDetailsService
findByUsername()
Memory
Database
© Faisal Memon | EmbarkX.com
Use Cases
→ Development and Testing
→ Small Applications
→ Prototyping
© Faisal Memon | EmbarkX.com
Benefits
→ Simplicity
→ Speed
→ Convenience
© Faisal Memon | EmbarkX.com
Thank you
© Faisal Memon | EmbarkX.com
UserDetailsService
UserDetailsManager
UserDetails
JdbcUserDetailsManager InMemoryUserDetailsManager
© Faisal Memon | EmbarkX.com
UserDetails
→ The UserDetails interface is a core component in Spring Security that
represents a user in the application
→ It provides necessary information about the user, such as username, password,
and authorities (roles)
String getUsername()
String getPassword()
Collection<? extends GrantedAuthority> getAuthorities()
boolean isAccountNonExpired()
boolean isAccountNonLocked()
boolean isCredentialsNonExpired()
boolean isEnabled()
© Faisal Memon | EmbarkX.com
User
→ User is a concrete implementation of the UserDetails interface provided by
Spring Security.
→ It is often used to create a UserDetails object with predefined username,
password, and authorities.
UserDetails
User
© Faisal Memon | EmbarkX.com
Interface
Class
UserDetailsService
UserDetailsManager
UserDetails
JdbcUserDetailsManager InMemoryUserDetailsManager
© Faisal Memon | EmbarkX.com
Interface
Class
UserDetailsService
UserDetailsManager
UserDetails
JdbcUserDetailsManager InMemoryUserDetailsManager
© Faisal Memon | EmbarkX.com
UserDetailsService
→ The UserDetailsService interface is responsible for retrieving user-related
data.
→ It has a single method that loads a user based on the username and returns a
UserDetails object.
UserDetailsService
UserDetailsManager
UserDetails
JdbcUserDetailsManager InMemoryUserDetailsManager
© Faisal Memon | EmbarkX.com
UserDetailsManager
→ The UserDetailsManager interface in Spring Security extends
UserDetailsService and provides additional methods for managing user accounts.
→ Provides additional capabilities for managing user accounts, such as creating,
updating, and deleting users, as well as changing passwords and checking for user
existence.
void createUser(UserDetails user)
void updateUser(UserDetails user)
void deleteUser(String username)
void changePassword(String oldPassword, String newPassword)
boolean userExists(String username)
© Faisal Memon | EmbarkX.com
Interface
Class
UserDetailsService
UserDetailsManager
UserDetails
JdbcUserDetailsManager InMemoryUserDetailsManager
© Faisal Memon | EmbarkX.com
JdbcUserDetailsManager
→ JdbcUserDetailsManager is a Spring Security implementation of the
UserDetailsManager interface that manages user details using a JDBC-based
data source
→ It provides methods to create, update, delete, and query user accounts, and it
interacts with the database using SQL queries.
InMemoryUserDetailsManager
→ InMemoryUserDetailsManager is another implementation of the
UserDetailsManager interface provided by Spring Security.
→ It manages user details entirely in memory, which means the user data is stored
in memory (RAM) and is not persistent across application restarts.
UserDetailsService
UserDetailsManager
UserDetails
JdbcUserDetailsManager InMemoryUserDetailsManager
© Faisal Memon | EmbarkX.com
→ Domain-Specific Requirements
→ Enhanced Security
© Faisal Memon | EmbarkX.com
Flexibility
Easier Testing
UserDetails
UserDetails
Thank you
© Faisal Memon | EmbarkX.com
Customer
Role: Can view account balance, transfer money, pay bills
Permissions: Access to personal account details, perform transactions.
Teller
Role: Can manage customer accounts, view transaction history, approve loans
Permissions: Access to customer information, modify accounts, approve transactions.
Admin
Role :Can create or delete user accounts, manage roles, oversee system operations
Permissions: Full system access, user and role management.
© Faisal Memon | EmbarkX.com
Importance
→ Security
→ Manageability
→ Scalability
→ Flexibility
© Faisal Memon | EmbarkX.com
API’s we need
HTTP Endpoint Description Parameters Response
Method
GET /getusers Retrieve all None List of User objects
users (HTTP 200)
Thank you
© Faisal Memon | EmbarkX.com
GrantedAuthority
SimpleGrantedAuthority
© Faisal Memon | EmbarkX.com
Method-Level Security
→ @PreAuthorize
→ @Secured
→ @RolesAllowed
→ @PostAuthorize
Example
import
org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class AdminService {
@PreAuthorize("hasRole('ADMIN')")
public void performAdminTask() {
// Code for admin task
}
}
© Faisal Memon | EmbarkX.com
Thank you
© Faisal Memon | EmbarkX.com
Techniques
→ URL-Based Restrictions
→ Method-Level Security
© Faisal Memon | EmbarkX.com
Method-Level Security
→ @PreAuthorize
→ @Secured
→ @RolesAllowed
→ @PostAuthorize
@PreAuthorize
@Service
public class DocumentService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public Document getDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("#document.owner == authentication.name")
public void updateDocument(Document document) {
// Method implementation
}
}
Example
© Faisal Memon | EmbarkX.com
@Service
public class DocumentService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public Document getDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("#document.owner == authentication.name")
public void updateDocument(Document document) {
// Method implementation
}
}
Example
© Faisal Memon | EmbarkX.com
@Service
public class DocumentService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public Document getDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("#document.owner == authentication.name")
public void updateDocument(Document document) {
// Method implementation
}
}
Example
© Faisal Memon | EmbarkX.com
@Service
public class DocumentService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public Document getDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("#document.owner == authentication.name")
public void updateDocument(Document document) {
// Method implementation
}
}
Example
© Faisal Memon | EmbarkX.com
@Service
public class DocumentService {
@PreAuthorize("hasRole('ADMIN')")
public void deleteDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public Document getDocument(Long documentId) {
// Method implementation
}
@PreAuthorize("#document.owner == authentication.name")
public void updateDocument(Document document) {
// Method implementation
}
}
© Faisal Memon | EmbarkX.com
@Secured
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
@Service
public class AccountService {
@Secured("ROLE_ADMIN")
public void createAccount(Account account) {
// Method implementation
}
@Secured({"ROLE_USER", "ROLE_ADMIN"})
public Account getAccount(Long accountId) {
// Method implementation
}
}
© Faisal Memon | EmbarkX.com
@RolesAllowed
import javax.annotation.security.RolesAllowed;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
@RolesAllowed("ROLE_MANAGER")
public void processOrder(Order order) {
// Method implementation
}
@RolesAllowed({"ROLE_USER", "ROLE_MANAGER"})
public Order getOrder(Long orderId) {
// Method implementation
}
}
© Faisal Memon | EmbarkX.com
@PostAuthorize
Checks the given expression after the method has been invoked
Example
© Faisal Memon | EmbarkX.com
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.stereotype.Service;
@Service
public class ReportService {
@PostAuthorize("returnObject.owner == authentication.name")
public Report getReport(Long reportId) {
// Method implementation
return report;
}
}
© Faisal Memon | EmbarkX.com
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.stereotype.Service;
@Service
public class MessageService {
@PreFilter("filterObject.owner == authentication.name")
public void sendMessages(List<Message> messages) {
// Method implementation
}
@PostFilter("filterObject.owner == authentication.name")
public List<Message> getMessages() {
// Method implementation
return messages;
}
}
© Faisal Memon | EmbarkX.com
Scenarios
Admin-Only Actions
Methods that should only be accessible to administrators can be secured using
@PreAuthorize or @Secured annotations with the ADMIN role.
Role-Based Access Control
Methods accessible by multiple roles can be defined using @PreAuthorize with
OR conditions or @Secured with multiple roles.
Scenarios
Post-Invocation Security
Methods that return data requiring post-invocation security checks can use
@PostAuthorize to enforce access control on the returned object.
Filtering Collections
Methods dealing with collections of objects can use @PreFilter and @PostFilter to
filter the collection based on security constraints.
© Faisal Memon | EmbarkX.com
Thank you
© Faisal Memon | EmbarkX.com
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/images/**").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
Example
© Faisal Memon | EmbarkX.com
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/images/**").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
Example
© Faisal Memon | EmbarkX.com
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/images/**").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
Example
© Faisal Memon | EmbarkX.com
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/images/**").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
Example
© Faisal Memon | EmbarkX.com
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/images/**").permitAll()
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
© Faisal Memon | EmbarkX.com
Definition Uses annotations to secure individual Configures security based on URL patterns in HTTP
methods. configuration.
Granularity Fine-grained control over individual methods. Coarse-grained control based on URL patterns.
Configuration Location Annotations on methods or classes in service Centralized in security configuration file.
or controller layers.
Flexibility Highly flexible with complex expressions Clear and straightforward URL-based rules.
using SpEL.
Impact on Business Directly couples security with business logic. Keeps security rules separate from business logic.
Logic
Management Can be verbose; requires annotations on Easier to manage with all rules in one configuration
Complexity each method. file.
Use Case Suitability Ideal for detailed control and complex Ideal for simple and maintainable URL-based security.
conditions.
© Faisal Memon | EmbarkX.com
Best Use Cases - Securing service methods accessed by various - Securing web applications with clear URL patterns
controllers. for different roles.
- Applying role-based access with additional - Enforcing access control on REST APIs based on
conditions. URL structures.
Cons - Requires annotations on each secured method. - Less granularity compared to method-level security.
- Tightly coupled with business logic. - Potential for overlapping or conflicting rules with
method-level security.
© Faisal Memon | EmbarkX.com
Need for Fine-Grained Control Method Level Security Provides detailed control over individual
methods.
Complex Security Logic Method Level Security Can apply complex conditions using SpEL.
Service Layer Security Method Level Security Ensures security checks directly at the service
layer.
Clear URL-Based Security RequestMatchers Approach Simple and clear rules based on URL patterns.
Simplicity and Maintainability RequestMatchers Approach Easier to manage without modifying business
logic.
© Faisal Memon | EmbarkX.com
Thank You
© Faisal Memon | EmbarkX.com
→ Maintaining Trust
© Faisal Memon | EmbarkX.com
Introduction to Custom
Filters
Rate Limiting
To prevent abuse of API endpoints, custom filters can implement rate limiting
logic
Geo-Blocking
Restrict access of API endpoints to certain locations
© Faisal Memon | EmbarkX.com
DisableEncodeUrlFilter
WebAsyncManagerIntegrationFilter
SecurityContextHolderFilter
HeaderWriterFilter
CorsFilter
CsrfFilter
LoggingFilter
LogoutFilter
OAuth2AuthorizationRequestRedirectFilter
OAuth2LoginAuthenticationFilter
AuthTokenFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
ExceptionTranslationFilter
AuthorizationFilter
© Faisal Memon | EmbarkX.com
Filter Lifecycle
Initialization
Request Processing
Cleanup
FILTER LIFECYCLE
© Faisal Memon | EmbarkX.com
Initialization
→ doFilter: This method
is called every time a
Request Processing request/response pair is
passed through the filter
Cleanup chain.
init(FilterConfig filterConfig)
This method exists in the Filter interface and is called by the Servlet container
destroy()
This method is part of the Filter interface and is called by the Servlet container
when the filter is being taken out of service
© Faisal Memon | EmbarkX.com
Using OncePerRequestFilter
Using GenericFilterBean
© Faisal Memon | EmbarkX.com
OncePerRequestFilter
→ OncePerRequestFilter is an abstract base class provided by Spring Security.
GenericFilterBean
→ GenericFilterBean is a base class provided by Spring Framework.
Conditional Filters
→ Use request attributes or headers to decide
whether to apply certain filters.
@Component
public class UserAgentFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String userAgent = request.getHeader("User-Agent");
if (userAgent != null && userAgent.contains("Mozilla")) {
// Additional processing for requests from browsers
System.out.println("Request from browser");
}
filterChain.doFilter(request, response);
}
}
© Faisal Memon | EmbarkX.com
@Component
public class DynamicIpWhitelistingFilter extends OncePerRequestFilter {
@Value("${whitelisted.ips}")
private List<String> whitelistedIps;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain)
throws ServletException, IOException {
String clientIp = request.getRemoteAddr();
if (!whitelistedIps.contains(clientIp)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
return;
}
filterChain.doFilter(request, response);
}
}
© Faisal Memon | EmbarkX.com
What is CSRF?
Unknowingly clicks
2 User Malicious Link
Browser
Forged request
3 Link Facebook
Processes request
4 Facebook User
© Faisal Memon | EmbarkX.com
Subscription Management
A malicious site the user visits sends a request to the service to unsubscribe or
change subscription preferences.
Posting on Forums
The attacker crafts a request to post spam or malicious content on the forum.
Example: The user visits a malicious site that sends a request to the forum’s post
endpoint.
E-commerce Purchases
The attacker crafts a request to purchase an item using the user's account.
Thank you
© Faisal Memon | EmbarkX.com
Browser
For every state-changing request the
CSRF token is included in the request Backend
3 User
Server
Sign In + Sign Up
What is Auditing
Auditing refers to the systematic recording, tracking, and
examination of activities and events within the system
© Faisal Memon | EmbarkX.com
Need
→ Security
→ Compliance
→ Accountability
→ Operational Efficiency
© Faisal Memon | EmbarkX.com
AuditLog
id
action
username
noteId
noteContent
timestamp
© Faisal Memon | EmbarkX.com
/api/audit GET ROLE_ADMIN Retrieve all audit logs. None List of AuditLog
objects
/api/audit/note/{id} GET ROLE_ADMIN Retrieve audit logs for a id (Path List of AuditLog
Variable, Long) objects
specific note by its ID.
© Faisal Memon | EmbarkX.com
PUT /update-lock-stat Updates the account userId (Long): ID of the user 200 OK: "Account lock status
us lock status of a user lock (boolean): Lock status updated"
GET /roles Retrieves all roles None 200 OK: List of roles
PUT /update-expiry-st Updates the account userId (Long): ID of the user 200 OK: "Account expiry status
atus expiry status of a user expire (boolean): Expiry status updated"
PUT /update-enabled-s Updates the account userId (Long): ID of the user 200 OK: "Account enabled status
tatus enabled status of a user enabled (boolean): Enabled status updated"
PUT /update-credentia Updates the credentials userId (Long): ID of the user 200 OK: "Credentials expiry status
ls-expiry-status expiry status of a user expire (boolean): Credentials expiry status updated"
PUT /update-password Updates the password of userId (Long): ID of the user 200 OK: "Password updated"
a user password (String): New password 400 BAD REQUEST: Error message
© Faisal Memon | EmbarkX.com
Password Reset
https://www.example.com/reset-password?token=123e4567-e89b-12d3-a456-4283
© Faisal Memon | EmbarkX.com
https://www.example.com/reset-password?token=123e4567-e89b-12d3-a456-4283
2.Token
Generation
5. Token
Validated
→ The form data (new password) is captured, and front end sends the new
password and token to the backend.
→ Frontend sends a POST request to the /auth/public/reset-password endpoint
with the new password and token
What do we need?
→ A component which allows users to request a password reset link by
submitting their email address [ForgotPassword]
→ A component allows users to reset their password using the token received in
the email [ResetPassword]
© Faisal Memon | EmbarkX.com
OAuth2
Problems
→ Security Risk
→ Limited Control
→ Inconvenience
© Faisal Memon | EmbarkX.com
What is OAuth?
OAuth (Open Authorization) is a standard protocol that allows
users to grant third-party applications access to their information
without sharing their passwords.
© Faisal Memon | EmbarkX.com
Summary
→ What: OAuth lets apps access your information without needing your
password.
→ Why: It’s safer because you don’t have to share your password with other apps.
→ Problem Solved: Before OAuth, apps needed your password to get your info,
which was risky.
→ How It Worked Before: You had to give your password to every app, which was
unsafe and inconvenient.
→ How OAuth Works Now: You log in through a trusted service (like Google),
give permission, and the app gets a special token to access your info without
needing your password.
© Faisal Memon | EmbarkX.com
Key Terms
→ Resource Owner (User): person who owns the account
→ Client: This is the application that requests access to the resource server on
behalf of the user.
© Faisal Memon | EmbarkX.com
Example
→ Resource Owner (User): You want to give PrintMyPhotos access to your
photos without giving them your Google account password
→ Third-Party Application: This is the application that wants to access your
photos to print them
→ Resource Server: This is the server that holds your photos and has the data
that PrintMyPhotos wants to access.
→ Authorization Server: This server handles the authentication (logging in) and
authorization (granting permissions) for Google services.
→ Client: This is the application that requests access to the resource server
(Google Photos) on behalf of the user.
© Faisal Memon | EmbarkX.com
1. You go to PrintMyPhotos and click on "Import
Photos from Google Photos."
USER
2.PrintMyPhotos
3. Google’s authorization server asks you to log sends you to
in (if you are not already logged in) and then Google’s
asks if you want to give PrintMyPhotos permission authorization
to access your Google Photos. server to log
in and grant
permission.
USER
Application Flow
2 Spring Security application.properties (Spring Defines OAuth2 Sets up: OAuth2 client registration.
Handles the Boot) client details
OAuth2 Redirect (client ID, secret,
redirect URI).
3 User is Redirected Spring Security Endpoint: Redirects user to Provider: GitHub or Google.
to OAuth2 Provider /oauth2/authorization/{registratio OAuth2 provider's
nId} authorization
page.
4 User Authenticates OAuth2 Provider's Authorization User logs in and Redirects back to: Application with authorization
with OAuth2 Page (External) authorizes the code.
Provider application.
5 Spring Security Spring Security Built-in Logic Exchanges Retrieves: User profile information.
Exchanges Code for authorization
Access Token code for access
token.
© Faisal Memon | EmbarkX.com
7 User is Redirected Redirection to Frontend Redirects user to a Includes: JWT token in URL query parameters.
to Frontend with specific route in React
JWT Token (e.g., /oauth2/redirect).
8 React Handles OAuth2RedirectHandler.js Handles redirect and Tasks: 1. Extract JWT token from URL.
OAuth2 Redirect (React) extracts JWT token. 2. Decode token to extract user information.
3. Store token and user info in local storage.
4. Update context state.
5. Redirect to protected route.
9 User Navigates to PrivateRoute.js (React) Ensures only Checks: Token in local storage.
Protected Route authenticated users can
access protected routes.
10 Setting Up Routes App.js (React) Set up routes for Login, Routes: /login: Login page.
in React OAuth2RedirectHandler, /oauth2/redirect: Handles OAuth2 redirect.
and protected routes /home and /: Protected routes.
using PrivateRoute.
© Faisal Memon | EmbarkX.com
Importance of Custom
Success Handler
Importance
→ User Registration and Management
→ Custom Redirection
© Faisal Memon | EmbarkX.com
→ Default Redirection
→ Security Context
© Faisal Memon | EmbarkX.com
Examples
→ Banking Apps
→ Email Services
Thank you
© Faisal Memon | EmbarkX.com
1. Login Attempt Enter Username and Password You start by entering your username and password on the login
page of the service you want to access.
2. Initial Authentication Verify Password The service verifies your password (something you know). If
correct, it proceeds to the next step.
3. Second Factor Request Prompt for Second Factor The service prompts you for a second factor, such as a code,
push notification, or biometric scan.
4. Receiving the Second Receive Code or Notification, Depending on the method, you receive a code via
Factor Perform Biometric Scan SMS/email/app or get a push notification or perform a scan.
5. Entering/Approving the Enter Code or Approve You enter the received code, approve the push notification, or
Second Factor Notification, Complete Scan complete the biometric scan.
6. Verification of Second Service Verifies Second Factor The service verifies the second factor. If it matches or is
Factor approved, it confirms your identity.
7. Access Granted Gain Access to Account Once both factors are verified, the service grants you access to
your account.
© Faisal Memon | EmbarkX.com
Example
Step Action Description
1. Open the Banking App Open the Banking App on your You start by opening your banking app on your phone.
phone
2. Enter Username and Enter Username and Password You enter your username and password.
Password
3. Receive SMS Code App Sends Code to Registered The app sends a code to your registered phone
Phone number.
4. Enter SMS Code Enter Code from SMS You enter the code from the SMS into the app.
5. Access Your Account App Verifies Code and Grants The app verifies the code and grants you access to
Access your account.
© Faisal Memon | EmbarkX.com
1. User User Registers an Account The user signs up for an account by providing their details (e.g., email,
Registration password).
2. 2FA Setup System Generates QR Code for After registration, the system generates a unique QR code linked to the
Initiation Google Authenticator user's account.
3. Scan QR User Scans QR Code with Google The user scans the QR code using the Google Authenticator app on
Code Authenticator their smartphone.
4. Generate 2FA Google Authenticator Generates a Google Authenticator generates a 6-digit code that changes every 30
Code 6-digit Code seconds.
5. Enter 2FA User Enters the Code from Google The user enters the 6-digit code from the Google Authenticator app into
Code Authenticator the Spring Boot application.
6. Verify 2FA System Verifies the Entered Code The Spring Boot application verifies the entered code against the one
Code generated by Google Authenticator.
© Faisal Memon | EmbarkX.com
7. Complete User Registration Completes if If the code is verified successfully, the user's account is fully registered
Registration Code is Verified with 2FA enabled.
8. Login Attempt User Enters Username and The user attempts to log in by entering their username and password.
Password
9. Prompt for System Prompts User to Enter 2FA After password verification, the system prompts the user to enter the
2FA Code Code 6-digit code from Google Authenticator.
10. Enter 2FA User Enters the Code from Google The user enters the 6-digit code from the Google Authenticator app.
Code Authenticator
11. Verify 2FA System Verifies the Entered Code The system verifies the entered code against the one generated by
Code Google Authenticator.
12. Access User Gains Access to the Account if If the code is verified successfully, the user gains access to their
Granted Code is Verified account.
© Faisal Memon | EmbarkX.com
POST /enable-2fa Enables 2FA for the logged-in None QR code URL for configuring 2FA
user
POST /disable-2fa Disables 2FA for the logged-in None "2FA disabled"
user
POST /verify-2fa Verifies the 2FA code for the int code "2FA verified" if valid, "Invalid 2FA
logged-in user code" if invalid
GET /user/2fa-status Gets the 2FA status for the None JSON object with the 2FA status, or
logged-in user "User not found"
POST /public/verify-2fa-login Verifies the 2FA code during int code, String "2FA verified" if valid, "Invalid 2FA
the login process using JWT jwtToken code" if invalid
© Faisal Memon | EmbarkX.com
Understanding Deployments
and How It Works
OUR APPLICATION
SERVER
SERVER
Response Back
Postman
© Faisal Memon | EmbarkX.com
OUR APPLICATION
SERVER
SERVER
S3 / Vercel / Netlify
RDS / Google Cloud
/ Azure
Response Back
Postman
If you think this course helped you, please do help provide an honest rating and
review of the course. Your insights help us improve and provide better content
for future learners.