The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • About
  • How CSRF Works? (Attack Flow)
  • CSRF vs XSS (Cross-Site Scripting)
  • Do Browsers Automatically Cascade Session-Related Data?
  • What Session-Related Data Does the Browser Automatically Include?
  • When Does a Browser Automatically Include Session Data?
  • Does the Browser Automatically Include JWT Tokens?
  • What If a JWT Is Stored in Cookies?
  • CSRF Attack Scenarios
  • 1. GET Request-Based CSRF
  • 2. POST Request-Based CSRF (Form Submission)
  • 3. CSRF via AJAX Requests
  • Mitigation Techniques in Spring Security
  • 1. CSRF Tokens (Synchronizer Token Pattern)
  • 2. SameSite Cookie Attribute
  • 3. CORS (Cross-Origin Resource Sharing) Restriction
  • 4. Double Submit Cookie Pattern
  • 5. User Authentication-Based Mitigation

Was this helpful?

  1. Spring
  2. Spring Features
  3. Spring Security

CSRF

About

Cross-Site Request Forgery (CSRF) is a web security vulnerability that tricks an authenticated user into performing unintended actions on a web application without their consent. It exploits the trust a web application has in the user’s browser session.

If a user is logged into a website, their browser automatically includes authentication tokens (cookies, session IDs, etc.) in requests made to that site. CSRF attacks leverage this by tricking users into making unintended requests, such as changing passwords, transferring money, or modifying settings.

CSRF and XSRF refer to the same security attack.

  • CSRF (Cross-Site Request Forgery) → Commonly used term.

  • XSRF (Cross-Site Request Forgery) → Some security experts and frameworks use this alternative name.

Why Two Names?

  • "Cross-Site" → "X-Site" abbreviation resulted in XSRF.

  • Some web frameworks, such as Angular, use XSRF-TOKEN as a CSRF protection mechanism.

How CSRF Works? (Attack Flow)

A typical CSRF attack follows these steps:

  1. User Authentication

    • A user logs into a web application (e.g., banking website).

    • The application issues an authentication session (usually via cookies). The browser stores authentication details (like session cookies, JWT, or OAuth tokens)

  2. User Visits a Malicious Site

    • The user unknowingly visits an attacker-controlled site or clicks a malicious link.

    • The attacker’s site contains an HTML form or script that sends a request to the victim's application using the authenticated session.

  3. Execution of Unauthorized Action

    • The victim's browser automatically includes authentication session in the request.

    • The web application processes the request, assuming it was made by the legitimate user.

Example of a malicious form triggering a CSRF attack:

<form action="https://bank.com/transfer" method="POST">
    <input type="hidden" name="account" value="attacker_account">
    <input type="hidden" name="amount" value="5000">
    <input type="submit">
</form>

If the victim is logged in, this request could transfer money without their knowledge.

CSRF vs XSS (Cross-Site Scripting)

Feature
CSRF
XSS

Target

Exploits authenticated users

Exploits the application itself

Attack Method

Forces user actions without consent

Injects malicious scripts into web pages

Requires User Authentication?

Yes

No

Mitigation

CSRF tokens, SameSite cookies

Input validation, Content Security Policy (CSP)

Do Browsers Automatically Cascade Session-Related Data?

Yes, browsers automatically include certain session-related data with requests based on security policies and authentication mechanisms. However, not all session-related data is automatically cascaded.

What Session-Related Data Does the Browser Automatically Include?

Type of Authentication

Automatically Sent by Browser?

Reason

Session Cookies

Yes

Cookies are automatically attached to requests based on domain and path rules.

Basic Authentication (Authorization Header: Basic username:password)

Yes (if cached)

Some browsers remember credentials and resend them.

Bearer Tokens (JWT in Authorization Header)

No

Browsers do NOT automatically attach JWT tokens.

API Keys in Headers

No

API Keys must be explicitly added by the client.

When Does a Browser Automatically Include Session Data?

  1. Cookies (Session-Based Authentication)

    • Browsers automatically send cookies with every request to the same domain and matching path.

    • Example: If a user logs into example.com, the session cookie is automatically sent with every subsequent request to example.com/api/*.

    Example: Cookie Auto-Sent by Browser

    GET /dashboard
    Host: example.com
    Cookie: JSESSIONID=abc123xyz
    • The browser automatically includes JSESSIONID, making it vulnerable to CSRF if not protected.

  2. Basic Authentication (If Cached by the Browser)

    • If a site uses Basic Authentication, some browsers cache the credentials and resend them automatically.

    • Example:

      Authorization: Basic dXNlcjpwYXNzd29yZA==
    • However, this behavior depends on browser settings and may not always happen.

Does the Browser Automatically Include JWT Tokens?

No, browsers do NOT automatically attach JWT tokens to requests.

  1. JWTs are stored manually (in localStorage, sessionStorage, or cookies).

  2. Unlike cookies, JWTs are not automatically sent unless explicitly added to the Authorization header.

  3. JWT-based authentication requires the client (JavaScript) to attach the token manually in API requests.

Example: Client Manually Sends JWT in Headers

fetch('https://api.example.com/protected', {
    method: 'GET',
    headers: {
        'Authorization': 'Bearer YOUR_JWT_TOKEN'
    }
});

Since JWTs are explicitly added, CSRF protection is NOT required.

What If a JWT Is Stored in Cookies?

If we store the JWT in a cookie with the HttpOnly and Secure flags, the browser will send it automatically like a session cookie.

Example: Storing JWT in a Cookie

Set-Cookie: access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...; HttpOnly; Secure; SameSite=Strict

If the JWT is stored in a cookie, CSRF protection is needed because the browser will automatically send it with requests/

CSRF Attack Scenarios

1. GET Request-Based CSRF

Many older web applications performed sensitive operations (like fund transfers, account modifications, etc.) using GET requests instead of POST, PUT, or DELETE. Since GET requests are automatically executed by browsers when an image, iframe, or script is loaded, attackers can craft a malicious URL that triggers an action when the victim visits a compromised page.

Example Scenario: Online Banking Fund Transfer

Let’s say an online banking system has an endpoint that allows users to transfer money using a simple GET request:

https://bank.com/transfer?to=attacker&amount=5000

If a user is logged into their banking account, this request automatically transfers $5000 to the attacker's account when executed.

Attack Execution

  1. Attacker Crafts a Malicious URL

    <img src="https://bank.com/transfer?to=attacker&amount=5000">
  2. User Visits a Malicious Website

    • The page automatically loads the <img> tag, sending a request to the bank.

    • The request includes the user’s authentication cookies (because it’s an image request to a trusted domain).

  3. Bank Processes the Request

    • Since the bank’s server sees a legitimate GET request from an authenticated user, it executes the fund transfer.

Mitigation Strategies

  • Use POST requests for any sensitive actions. GET requests should only retrieve data, never modify it.

  • Implement CSRF tokens, ensuring that every action requires a unique, server-generated token.

  • SameSite Cookie Policy, which prevents cookies from being sent with cross-site requests.

2. POST Request-Based CSRF (Form Submission)

  • Many web applications process sensitive operations using POST requests, but they do not validate the source of these requests.

  • Attackers can embed hidden forms on malicious sites that auto-submit upon page load, tricking users into performing unintended actions.

Example Scenario: Changing Email Address

Assume a website allows users to change their email address via the following form:

htmlCopyEdit<form action="https://example.com/change-email" method="POST">
    <input type="hidden" name="email" value="attacker@example.com">
    <input type="submit" value="Change Email">
</form>

An attacker can create a similar form on their malicious site and auto-submit it when the victim visits.

Attack Execution

  1. Attacker Embeds a Hidden Form on a Malicious Website

    <form action="https://example.com/change-email" method="POST">
        <input type="hidden" name="email" value="attacker@example.com">
        <script>document.forms[0].submit();</script>
    </form>
  2. User Visits the Malicious Page

    • The script executes immediately, submitting the form without user interaction.

  3. Server Accepts the Request

    • Since the user is authenticated, their cookies are automatically sent with the request.

    • The email gets changed without their knowledge.

Mitigation Strategies

  • CSRF Tokens: Every form submission must include a unique, server-generated token.

  • SameSite Cookies: Prevent browsers from sending cookies in cross-site requests.

  • Referrer Header Validation: Check that the request originated from the same domain.

3. CSRF via AJAX Requests

Modern applications often use AJAX requests to communicate with the server dynamically. If CORS (Cross-Origin Resource Sharing) is misconfigured, an attacker can craft a malicious JavaScript scriptthat triggers API requests from an external site using the victim’s session.

Example Scenario: Unauthorized Money Transfer via Fetch API

A bank provides an API for transferring funds via AJAX:

fetch("https://bank.com/transfer", {
    method: "POST",
    credentials: "include",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ to: "attacker", amount: 5000 })
});

If the user is authenticated, the browser automatically includes session cookies in the request, making it valid.

Attack Execution

  1. Attacker Hosts Malicious JavaScript

    fetch("https://bank.com/transfer", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ to: "attacker", amount: 5000 })
    });
  2. User Visits a Malicious Page

    • The script executes automatically in the background.

    • The browser sends a request to bank.com with the user’s cookies.

  3. The Bank’s Server Processes the Request

    • Since the request looks legitimate, the transaction is completed.

Mitigation Strategies

  • CSRF Tokens: Require a unique token for all AJAX requests.

  • CORS Configuration: Restrict APIs to trusted domains.

  • SameSite Cookies: Prevent cookies from being sent with cross-origin requests.

  • Origin Header Validation: Ensure that requests originate from the same domain.

Mitigation Techniques in Spring Security

Cross-Site Request Forgery (CSRF) is a critical web security vulnerability that allows attackers to trick users into performing unintended actions on authenticated websites. To mitigate CSRF attacks effectively, web applications should implement a combination of the following security measures.

1. CSRF Tokens (Synchronizer Token Pattern)

A CSRF token is a randomly generated unique token that the server generates and associates with a user session. Every sensitive request (e.g., form submission, API call) must include this token. The server validates the token before processing the request.

How CSRF Tokens Work?

  1. Server generates a CSRF token for each user session.

  2. The token is embedded in all forms and AJAX requests.

  3. On submission, the server validates the CSRF token before processing the request.

  4. If the token is missing or invalid, the request is rejected.

Implementation Steps

  1. Default CSRF Configuration (No Need to Manually Enable)

    Spring Security enables CSRF protection by default. Any state-changing HTTP requests (POST, PUT, DELETE) require a valid CSRF token.

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {
    
        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/public/**").permitAll()
                    .anyRequest().authenticated()
                )
                .csrf(Customizer.withDefaults()) // CSRF protection enabled (default)
                .formLogin(Customizer.withDefaults()) // Enables login
                .logout(Customizer.withDefaults()); // Enables logout
    
            return http.build();
        }
    }
  2. Generate a CSRF Token

    • When a user logs in or starts a session, the server generates a unique CSRF token and stores it in the session.

    • Example in Java (Spring Security):

      @GetMapping("/form")
      public String getForm(Model model, HttpSession session) {
          String csrfToken = UUID.randomUUID().toString();
          session.setAttribute("csrfToken", csrfToken);
          model.addAttribute("csrfToken", csrfToken);
          return "form";
      }
  3. Embed the CSRF Token in Requests

    • In HTML forms:

      <form action="/transfer" method="POST">
          <input type="hidden" name="csrfToken" value="${csrfToken}">
          <button type="submit">Transfer</button>
      </form>
    • In AJAX requests:

      fetch('/transfer', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
          body: JSON.stringify({ to: 'attacker', amount: 5000 })
      });
  4. Verify CSRF Token on the Server

    • When a request is received, the server checks whether the provided token matches the token stored in the session.

    • Example in Java (Spring Security):

      @PostMapping("/transfer")
      public ResponseEntity<String> transfer(@RequestParam String csrfToken, HttpSession session) {
          String sessionToken = (String) session.getAttribute("csrfToken");
          if (sessionToken == null || !sessionToken.equals(csrfToken)) {
              return ResponseEntity.status(HttpStatus.FORBIDDEN).body("CSRF Token Mismatch");
          }
          // Process transaction
          return ResponseEntity.ok("Transfer successful");
      }

2. SameSite Cookie Attribute

The SameSite attribute in HTTP cookies prevents cookies from being sent with cross-site requests, blocking unauthorized CSRF attempts.

Implementation

When setting cookies, configure the SameSite attribute as Strict or Lax:

Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict

SameSite Value

Behavior

Example Scenario

Strict

Cookies are sent only for requests from the same site.Cross-site requests won't send cookies.

You are logged into bank.com. If an attacker tricks you into clicking a malicious link from hacker.com, your session cookie won't be sent to bank.com, preventing CSRF.

Lax

Cookies are sent for same-site and top-level GET requests.

You click a link to bank.com from news.com. Since it's a top-levelnavigation, cookies are sent. However, cookies are not sent for embedded resources (like images, scripts, or AJAX requests) from other sites.

None

Cookies are sent with all requests, even from different websites, but must be marked as Secure.

If a web app needs cross-site requests (e.g., APIs used by multiple domains), it must use None and Secure to prevent security risks.

Example in Spring Boot

@Bean
public CookieSerializer cookieSerializer() {
    DefaultCookieSerializer serializer = new DefaultCookieSerializer();
    serializer.setSameSite("Strict");
    return serializer;
}
  • Simple to implement with no extra tokens.

  • Works well with browsers supporting the SameSite attribute.

  • May break legitimate third-party integrations.

  • Not supported by all legacy browsers.

3. CORS (Cross-Origin Resource Sharing) Restriction

CORS defines which domains are allowed to make requests to a web server. Properly configuring CORS prevents CSRF attacks via AJAX requests.

Implementation

  1. Restrict Allowed Origins

    • Only allow requests from trusted origins.

    @Configuration
    public class CorsConfig {
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/api/**")
                        .allowedOrigins("https://trustedsite.com")
                        .allowedMethods("GET", "POST");
                }
            };
        }
    }
  2. Validate Origin and Referer Headers

    • Ensure that requests originate from an authorized domain.

    @PostMapping("/transfer")
    public ResponseEntity<String> secureTransfer(@RequestHeader("Origin") String origin) {
        if (!origin.equals("https://trustedsite.com")) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Invalid Origin");
        }
        return ResponseEntity.ok("Transfer Successful");
    }
  • Effective against unauthorized AJAX-based CSRF attacks.

  • Works well for API-based applications.

  • Not effective for traditional form-based CSRF attacks.

  • Requires proper configuration to avoid breaking legitimate requests.

4. Double Submit Cookie Pattern

  • The server sets a CSRF token as a cookie.

  • The frontend reads this cookie and includes it in every request as a header.

  • The server validates that both values match.

Implementation

  1. Set CSRF Token as a Cookie

    @GetMapping("/csrf-token")
    public ResponseEntity<Void> setCsrfToken(HttpServletResponse response) {
        String csrfToken = UUID.randomUUID().toString();
        Cookie csrfCookie = new Cookie("XSRF-TOKEN", csrfToken);
        csrfCookie.setHttpOnly(false);
        csrfCookie.setPath("/");
        response.addCookie(csrfCookie);
        return ResponseEntity.ok().build();
    }
  2. Frontend Reads and Includes CSRF Token in Requests

    const csrfToken = document.cookie.split('; ')
        .find(row => row.startsWith('XSRF-TOKEN='))
        ?.split('=')[1];
    
    fetch('/transfer', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
        body: JSON.stringify({ to: 'attacker', amount: 5000 })
    });
  3. Verify Token on the Server

    @PostMapping("/transfer")
    public ResponseEntity<String> validateCsrf(@RequestHeader("X-CSRF-TOKEN") String csrfToken, @CookieValue("XSRF-TOKEN") String csrfCookie) {
        if (!csrfToken.equals(csrfCookie)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("CSRF Token Mismatch");
        }
        return ResponseEntity.ok("Transfer Successful");
    }
  • Works well for single-page applications (SPAs).

  • Does not require session storage.

  • Less secure than synchronizer tokens (an attacker can read cookies in some cases).

5. User Authentication-Based Mitigation

  • Require multi-factor authentication (MFA) for sensitive actions.

  • Force re-authentication before critical actions like fund transfers.

Example: MFA Prompt

@PostMapping("/transfer")
public ResponseEntity<String> secureTransfer(@RequestHeader("Authorization") String token) {
    if (!mfaService.isVerified(token)) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("MFA Required");
    }
    return ResponseEntity.ok("Transfer Successful");
}
  • Highly secure for sensitive operations.

  • Provides an extra layer beyond CSRF protection.

  • Requires user interaction, which can reduce usability.

PreviousSecurity Filters and InterceptorsNextReal-World CSRF Attacks & Prevention

Last updated 2 months ago

Was this helpful?