0% found this document useful (0 votes)
22 views

Spring+Security+Masterclass+Slides

The document outlines the usage policy for course materials provided by Faisal Memon at EmbarkX, emphasizing personal use, prohibition of unauthorized sharing, and the protection of intellectual property. It also covers key concepts related to Spring Security, including authentication, authorization, filters, and various authentication providers, along with their importance and functionalities. Additionally, it discusses the structure and management of user details within Spring Security, highlighting the roles of UserDetailsService and UserDetailsManager.

Uploaded by

Ghulam Sarwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Spring+Security+Masterclass+Slides

The document outlines the usage policy for course materials provided by Faisal Memon at EmbarkX, emphasizing personal use, prohibition of unauthorized sharing, and the protection of intellectual property. It also covers key concepts related to Spring Security, including authentication, authorization, filters, and various authentication providers, along with their importance and functionalities. Additionally, it discusses the structure and management of user details within Spring Security, highlighting the roles of UserDetailsService and UserDetailsManager.

Uploaded by

Ghulam Sarwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 217

© Faisal Memon | EmbarkX.

com

Spring Security Masterclass

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com
Usage Policy for Course Materials

Instructor: Faisal Memon


Company: EmbarkX.com

1. Personal Use Only


The materials provided in this course, including but not limited to PDF presentations, are intended for your personal use only. They are to be
used solely for the purpose of learning and completing this course.

2. No Unauthorized Sharing or Distribution


You are not permitted to share, distribute, or publicly post any course materials on any websites, social media platforms, or other public
forums without prior written consent from the instructor.

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: Importance


& Benefits

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Spring Security

Authentication and Authorization

Protection Against Common Threats

Password Storage

Integration with Spring Ecosystem


© Faisal Memon | EmbarkX.com

Imagine doing all by yourself


© Faisal Memon | EmbarkX.com

Why Use Spring Security


→ Comprehensive and Customizable

→ Community and Support

→ Declarative Security

→ Integration Capabilities
© Faisal Memon | EmbarkX.com

Why Use Spring Security


→ Regular Updates

→ Ease of Use with Spring Boot


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

PRINCIPAL AND
AUTHENTICATION OBJECT

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

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

→Details about the user


Authentication
Object
© Faisal Memon | EmbarkX.com

Understanding Filters and


Filter Chain

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Dispatcher
CLIENT Controller
Servlet

Filter Chain

Rest of the app


[Services + DB]
Response Back
© Faisal Memon | EmbarkX.com

Dispatcher
CLIENT Controller
Servlet

Filter Chain

Rest of the app


[Services + DB]
Response Back
© Faisal Memon | EmbarkX.com
Filter

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.

→ A Filter Chain is a sequence of filters


that an HTTP request and response pass
through before reaching the targeted
resource and after the resource has
generated a response.

Filter Chain
© Faisal Memon | EmbarkX.com

How Filters and Filter Chains work?


→ The first filter in the chain receives the request and performs its processing.

→ After processing, the filter calls chain.doFilter(request, response) to pass the


request to the next filter in the chain.

→ 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

→ Pre-Processing and Post-Processing

→ Request and Response Manipulation

→ Separation of Concerns
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Filters that you should be


aware of

Faisal Memon (EmbarkX)


© 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

Why Learning these is important


→ Demonstrates In-Depth Knowledge

→ Problem-Solving Skills

→ Security Best Practices


© Faisal Memon | EmbarkX.com

Helps with Right


Configuration, Customization
and Troubleshooting
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Basic Authentication

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

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

username:password Base64 Encoding Base64 Encoded

Basic <base64 encoded value>

Authorization Header
© Faisal Memon | EmbarkX.com

Structuring Thoughts

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

HTTP Endpoint Description Request Request Parameter Response


Method Body

POST /api/notes Create a new String @AuthenticationPrincipal Note (created


note content UserDetails userDetails note)

GET /api/notes Retrieve all None @AuthenticationPrincipal List<Note>


notes for the UserDetails userDetails (user's notes)
logged-in user

PUT /api/notes/{noteId} Update an String @AuthenticationPrincipal Note (updated


existing note content UserDetails userDetails note)

DELETE /api/notes/{noteId} Delete a note None @AuthenticationPrincipal void


UserDetails userDetails
© Faisal Memon | EmbarkX.com

Authentication Providers

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Authentication Providers in Spring


Security are components handle the
actual verification of credentials provided
by a user during the login process
© Faisal Memon | EmbarkX.com

Key Responsibilities
→ Authenticate the User

→ Create Authentication Token


© Faisal Memon | EmbarkX.com

Importance
→ Flexibility

→ Separation of Concerns

→ Extensibility

→ Security
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Authentication Providers

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Authentication Providers
→ DaoAuthenticationProvider

→ InMemoryAuthenticationProvider

→ LdapAuthenticationProvider

→ ActiveDirectoryLdapAuthenticationProvider
© Faisal Memon | EmbarkX.com

Authentication Providers
→ PreAuthenticatedAuthenticationProvider

→ OAuth2AuthenticationProvider
© Faisal Memon | EmbarkX.com

In Memory Authentication

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

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

Core Classes & Interfaces for


user management

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com
Interface
Class

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 = User.withUsername("user")


.password("{noop}password")
.authorities("ROLE_USER")
.build();
© Faisal Memon | EmbarkX.com
Interface
Class

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.

UserDetails loadUserByUsername(String username)


throws UsernameNotFoundException
© Faisal Memon | EmbarkX.com
Interface
Class

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.

void createUser(UserDetails user)


void updateUser(UserDetails user)
void deleteUser(String username)
void changePassword(String oldPassword, String newPassword)
boolean userExists(String username)
UserDetails loadUserByUsername(String username)
© Faisal Memon | EmbarkX.com

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.

void createUser(UserDetails user)


void updateUser(UserDetails user)
void deleteUser(String username)
void changePassword(String oldPassword, String newPassword)
boolean userExists(String username)
UserDetails loadUserByUsername(String username)
© Faisal Memon | EmbarkX.com
Interface
Class

UserDetailsService

UserDetailsManager

UserDetails

JdbcUserDetailsManager InMemoryUserDetailsManager
© Faisal Memon | EmbarkX.com

Custom User Model

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Why Custom User Model


→ Extended User Information

→ Domain-Specific Requirements

→ Custom Authentication and Authorization Logic

→ Integration with Other Systems

→ Enhanced Security
© Faisal Memon | EmbarkX.com

Benefits of a Custom User Model

Flexibility

Better Code Organization

Easier Testing

Improved User Experience


© Faisal Memon | EmbarkX.com
Interface
Class

UserDetails

User Custom User Model


© Faisal Memon | EmbarkX.com
Interface
Class

UserDetails

User Custom User Model


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Role Based Authorization

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Role-based authorization is a method of


restricting access to resources based on
the roles assigned to users
© Faisal Memon | EmbarkX.com

Online Banking System

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)

PUT /update-r Update a userId (Long, required), Success message


ole user's role roleName (String, (HTTP 200)
required)
GET /user/{id} Retrieve a id (Path variable, Long, UserDTO object
user by ID required) (HTTP 200)
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Inbuilt classes and interfaces


For Authorization

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com
Interface
Class

GrantedAuthority

SimpleGrantedAuthority
© Faisal Memon | EmbarkX.com

Managing Access with


Annotations

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Spring Security provides


annotations to secure methods in
your services or controllers.
© Faisal Memon | EmbarkX.com

Method-Level Security
→ @PreAuthorize

→ @Secured

→ @RolesAllowed

→ @PostAuthorize

→ @PreFilter and @PostFilter


© Faisal Memon | EmbarkX.com

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

Restricting Admin Actions

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Techniques
→ URL-Based Restrictions

→ Method-Level Security
© Faisal Memon | EmbarkX.com

Method Level Security

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Method-level security in Spring


Security allows you to apply security
constraints directly on methods within
your services or controllers
© Faisal Memon | EmbarkX.com

Method-Level Security
→ @PreAuthorize

→ @Secured

→ @RolesAllowed

→ @PostAuthorize

→ @PreFilter and @PostFilter


© Faisal Memon | EmbarkX.com

@PreAuthorize

Checks the given expression before entering the method


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
}
}
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

Simpler alternative to @PreAuthorize, used to specify roles directly


Example
© Faisal Memon | EmbarkX.com

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

Specifies roles allowed to invoke the method


Example
© Faisal Memon | EmbarkX.com

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

@PreFilter and @PostFilter


The @PreFilter and @PostFilter annotations filter collections or
arrays passed as method arguments or returned by the method.
Example
© 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.

Ownership and Contextual Access


Methods that require checks on ownership or other contextual conditions can use
@PreAuthorize with SpEL expressions to enforce these rules.
© Faisal Memon | EmbarkX.com

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

URL Based Restrictions

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Spring Security allows you to configure


URL-based restrictions in your security
configuration.
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();
}
}
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

Method Level Security vs


RequestMatchers

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Method Level Security RequestMatchers Approach

Definition Uses annotations to secure individual Configures security based on URL patterns in HTTP
methods. configuration.

Key @PreAuthorize, @PostAuthorize, requestMatchers


Annotations/Methods @Secured, @RolesAllowed

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

Method Level Security RequestMatchers Approach

Examples @PreAuthorize("hasRole('ROLE_ADMIN')") .requestMatchers("/admin/**").hasRole("ADMIN")


@Secured("ROLE_ADMIN")

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.

Pros - Provides detailed access control. - Centralized management.


- Can apply complex security logic. - Clear URL-based rules.
- Ensures security at the business logic layer. - Less intrusive to business logic.

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

Scenario Preferred Approach Reasoning

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.

Centralized Security Management RequestMatchers Approach Centralized configuration in one place.

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

Combining Both Approaches


© Faisal Memon | EmbarkX.com

Thank You
© Faisal Memon | EmbarkX.com

Password Security and


Password Encoding

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Password security refers to the


measures and practices used to
protect passwords from being stolen,
guessed, or otherwise compromised
© Faisal Memon | EmbarkX.com

Why is Password Security Important?


→ Protection of Sensitive Data

→ Prevent Unauthorized Access

→ Compliance and Legal Requirements

→ Maintaining Trust
© Faisal Memon | EmbarkX.com

Password encoding is the process of


transforming a password into a
different format using an algorithm.
© Faisal Memon | EmbarkX.com

Introduction to Custom
Filters

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Spring Security filters are Java


components that intercept HTTP
requests and responses
© Faisal Memon | EmbarkX.com

Custom Security Filter Scenarios


Custom Authentication and Authorization
Custom filters can implement specialized authentication logic, such as
token-based authentication, custom headers, or multi-factor authentication
(MFA)
© Faisal Memon | EmbarkX.com

Custom Security Filter Scenarios

Rate Limiting
To prevent abuse of API endpoints, custom filters can implement rate limiting
logic

IP Whitelisting and Blacklisting


Restrict access of API endpoints to certain IP addresses

Geo-Blocking
Restrict access of API endpoints to certain locations
© Faisal Memon | EmbarkX.com

Custom Security Filter Scenarios

Compliance and Logging


Custom filters can be used to implement detailed logging mechanisms for
compliance purposes

Integration with External Systems


Custom filters can integrate with external systems or third-party services

Handling Cross-Cutting Concerns


Custom filters can handle cross-cutting concerns such as logging, transaction
management, or modifying requests and responses
© Faisal Memon | EmbarkX.com

Default Filter Chain

Faisal Memon (EmbarkX)


© 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

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Filters are part of the Servlet API and


have a well-defined lifecycle managed
by the Servlet container.
© Faisal Memon | EmbarkX.com

Initialization

Request Processing

Cleanup

FILTER LIFECYCLE
© Faisal Memon | EmbarkX.com

Initialization → init: This method is


called once when the
Request Processing
filter is first created.
Cleanup
→It is used to perform
any necessary setup or
FILTER LIFECYCLE
resource allocation.
© 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.

FILTER LIFECYCLE →It performs the main


filtering task
© Faisal Memon | EmbarkX.com

Initialization → destroy: This method


is called once when the
Request Processing
filter is being removed
Cleanup
from service.

→It is used to release


FILTER LIFECYCLE
any resources allocated
© Faisal Memon | EmbarkX.com

Where do these methods exist

init(FilterConfig filterConfig)
This method exists in the Filter interface and is called by the Servlet container

doFilter(ServletRequest request, ServletResponse response, FilterChain chain)


This method also exists in the Filter interface and is called by the Servlet
container for each request/response pair that passes through the filter

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

Inbuilt Classes for Filter


Implementation

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Inbuilt Classes for Filter Implementation

Using OncePerRequestFilter

Using GenericFilterBean
© Faisal Memon | EmbarkX.com

OncePerRequestFilter
→ OncePerRequestFilter is an abstract base class provided by Spring Security.

→ Ensures that the filter is executed only once per request.

→ Simplifies filter implementation by handling repeated invocations.


© Faisal Memon | EmbarkX.com

GenericFilterBean
→ GenericFilterBean is a base class provided by Spring Framework.

→ It provides a simpler way to create filters without directly implementing the


Filter interface.

→ Requires implementing the doFilter method.


© Faisal Memon | EmbarkX.com

Adding Filters into FilterChain


→ addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter)

→ addFilterAfter(Filter filter, Class<? extends Filter> afterFilter)


© Faisal Memon | EmbarkX.com

Advanced Custom Filter


Scenarios

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Custom Filter Scenarios

Combining Multiple Filters

Conditional Filters Based on Request Attributes

Dynamic Filter Configuration


© Faisal Memon | EmbarkX.com

Combining Multiple Filters


→ Ensure the correct order of filters to maintain the
logical flow and prevent bypassing security measures.

→ Combine filters to handle complex scenarios that


require multiple checks or actions.
© Faisal Memon | EmbarkX.com

Conditional Filters
→ Use request attributes or headers to decide
whether to apply certain filters.

→ Implement logic within filters to conditionally


process requests.
© Faisal Memon | EmbarkX.com

@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

Dynamic Filter Configuration


→ Use Spring's configuration properties or
externalized configuration to control filter behavior.

→ Enable or disable filters based on runtime


conditions.
© Faisal Memon | EmbarkX.com
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@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?

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

CSRF (Cross-Site Request Forgery) is


a type of malicious exploit of a website
where unauthorized commands are
transmitted from a user
© Faisal Memon | EmbarkX.com

Logs in & authenticates session


1 User Facebook

Unknowingly clicks
2 User Malicious Link

Browser

Forged request
3 Link Facebook

Processes request
4 Facebook User
© Faisal Memon | EmbarkX.com

Bank Transfer Attack


The user visits a malicious website while logged in. This site contains an embedded
script that sends a POST request to the bank’s transfer money endpoint.

<!-- Malicious website -->


<img src="http://trustedbank.com/transfer?amount=1000&toAccount=attacker"
style="display:none;" />
© Faisal Memon | EmbarkX.com

Changing User Email


The user clicks on a link in an email that directs them to a malicious website. This
site sends a request to change the user’s email address to the attacker's email.

<!-- Malicious website -->


<form action="http://socialmedia.com/change-email" method="POST">
<input type="hidden" name="email" value="[email protected]" />
<input type="submit" value="Change Email" />
</form>
© Faisal Memon | EmbarkX.com

Subscription Management
A malicious site the user visits sends a request to the service to unsubscribe or
change subscription preferences.

<!-- Malicious website -->


<img src="http://onlineservice.com/unsubscribe" style="display:none;" />
© Faisal Memon | EmbarkX.com

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.

<!-- Malicious website -->


<form action="http://forum.com/post" method="POST">
<input type="hidden" name="content" value="Buy cheap products at
spammywebsite.com" />
<input type="submit" value="Post" />
</form>
© Faisal Memon | EmbarkX.com

E-commerce Purchases
The attacker crafts a request to purchase an item using the user's account.

<!-- Malicious website -->


<form action="http://ecommerce.com/purchase" method="POST">
<input type="hidden" name="item" value="expensive-gadget" />
<input type="hidden" name="quantity" value="1" />
<input type="submit" value="Buy" />
</form>
© Faisal Memon | EmbarkX.com

Impact of Successful CSRF Attacks


→ Financial Loss
→ Compromised User Accounts
→ Reputation Damage
→ Service Disruption
→ Data Integrity Issues
→ Legal and Compliance Risks
© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

What is CSRF Protection?

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

CSRF (Cross-Site Request Forgery)


protection is essential to prevent
unauthorized actions in web
applications when a user is
authenticated
© Faisal Memon | EmbarkX.com

User logs in and server generates unique


token Backend
1 User
Server

This token is stored on the client-side and


Server side Backend
2 User
Server

Browser
For every state-changing request the
CSRF token is included in the request Backend
3 User
Server

Retrieves the CSRF token from the


request and validates it Backend
4 User
Server
If the tokens match, server processes it
© Faisal Memon | EmbarkX.com

Sign In + Sign Up

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

HTTP Path Description Request Body Response Body


Method

POST /public/signin Authenticate a user and return a LoginRequest LoginResponse


JWT token

POST /public/signup Register a new user SignupRequest MessageResponse

GET /username Get the current authenticated N/A String


username

GET /user Get details of the authenticated N/A UserInfoResponse


user
© Faisal Memon | EmbarkX.com

Auditing and it’s needed

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

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

Endpoint HTTP Authorization Description Parameters Response


Method

/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

Admin Actions | Building the


Backend

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

HTTP Endpoint Description Parameters Response


Method

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

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Password Reset URL

https://www.example.com/reset-password?token=123e4567-e89b-12d3-a456-4283
© Faisal Memon | EmbarkX.com

Password Reset URL

https://www.example.com/reset-password?token=123e4567-e89b-12d3-a456-4283

Front end URL Token


© Faisal Memon | EmbarkX.com

1. User Requests Password Reset

2.Token
Generation

3. Email with Reset Link Sent

USER 4. User Clicks the Link SERVER

5. Token
Validated

6. Password update and confirmation


© Faisal Memon | EmbarkX.com

Password Reset Functionality


| The Frontend

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Reset Password Flow


→ The user clicks the link in the reset email and is redirected to the reset
password page

→ The reset token is extracted from the URL

→ 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

→ Password updated and user sees success message


© Faisal Memon | EmbarkX.com

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

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

You had to share your


credentials all the time
© Faisal Memon | EmbarkX.com

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

Why is OAuth Needed?


OAuth is needed to enable secure and easy access to user
information by third-party applications without compromising the
user's credentials (like passwords).
© Faisal Memon | EmbarkX.com

OAuth solves the problem of sharing


sensitive login credentials directly
with third-party applications.
© 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

→ Third-Party Application: This is the application that wants to access to your


account
→ Resource Server: This is the server that holds data that application wants to
access.
→ Authorization Server: This server handles the authentication (logging in) and
authorization (granting permissions)

→ 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.

4. You agree and grant permission. Google’s


GOOGLE APP
authorization server then sends an authorization
code back to PrintMyPhotos.

USER

5. PrintMyPhotos sends the authorization code to


Google’s authorization server and requests an
access token.

6. PrintMyPhotos uses this access token to request


your photos from the Google Photos resource server.
© Faisal Memon | EmbarkX.com

Application Flow

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Step Description Component Action Details

1 User Initiates Login.js (React) User clicks "Login Redirects to:


OAuth2 Login with GitHub" or http://localhost:8080/oauth2/authorization/{pro
"Login with vider}
Google" button.

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

Step Description Component Action Details

6 OAuth2LoginSucces OAuth2LoginSuccessHandler Handles successful Tasks:


sHandler is Invoked .java (Spring Boot) authentication. 1. Check if user exists in the database.
2. Register new user if not exists.
3. Generate JWT token.
4. Redirect to frontend with JWT token.

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

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Importance
→ User Registration and Management

→ Security Context Update

→ JWT Token Generation

→ Custom Redirection
© Faisal Memon | EmbarkX.com

What Happens if Not Defined


→ No Custom User Handling

→ No JWT Token Generation

→ Default Redirection

→ Security Context
© Faisal Memon | EmbarkX.com

What is Multi Factor


Authentication

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Multi-Factor Authentication (MFA) is a


security process that requires you to
prove your identity in multiple ways
before accessing an account or system
© Faisal Memon | EmbarkX.com

How does it work?


Something you know: This is usually a password or a
PIN.
Something you have: This could be a smartphone, a
security token, or a key card.

Something you are: This involves biometric verification,


like a fingerprint or facial recognition.
© Faisal Memon | EmbarkX.com

Examples
→ Banking Apps

→ Email Services

→ Social Media Platforms


© Faisal Memon | EmbarkX.com

Thank you
© Faisal Memon | EmbarkX.com

Multi Factor Authentication


Flow

Faisal Memon (EmbarkX)


Flow
© Faisal Memon | EmbarkX.com

Step Action Description

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

General Flow of 2FA with Google Authenticator


Step Action Description

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

General Flow of 2FA with Google Authenticator


Step Action Description

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

Steps for our application


→ Enable MFA Flow

→ Login with MFA Flow


© Faisal Memon | EmbarkX.com

Enable MFA Flow

Enable MFA Generate Display QR


Enter Code
Request Secret Code

Enable MFA Verify Code


© Faisal Memon | EmbarkX.com

Login with MFA Flow

Login Check MFA Prompt for


Initial Auth
Attempt Status Code

Access Verify Code


Granted
© Faisal Memon | EmbarkX.com

Enable MFA Flow

Enable MFA Generate Display QR


Enter Code
Request Secret Code

Enable MFA Verify Code


© Faisal Memon | EmbarkX.com

Login with MFA Flow

Login Check MFA Prompt for


Initial Auth
Attempt Status Code

Access Verify Code


Granted
© Faisal Memon | EmbarkX.com

Setting up the Backend API’s

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

HTTP Endpoint Description Request Response


Method Parameters

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

Faisal Memon (EmbarkX)


© Faisal Memon | EmbarkX.com

Deployment is the process of


moving software from the
development environment to the
production environment where it
can be used by end-users.
© Faisal Memon | EmbarkX.com

OUR APPLICATION

Controller Service Repository


Database
REACT
Browser All Controllers All Services All Repositories
APP

SERVER

SERVER

Response Back

Postman
© Faisal Memon | EmbarkX.com

OUR APPLICATION

Controller Service Repository


Database
REACT
Browser All Controllers All Services All Repositories
APP

SERVER

SERVER
S3 / Vercel / Netlify
RDS / Google Cloud
/ Azure

Response Back

Postman

AWS / Render / GCP


© Faisal Memon | EmbarkX.com

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.

We appreciate your support and look forward to hearing your thoughts!

You might also like