Spring Security CSRF and CORS Interview Questions and Answers

Master CSRF and CORS in Spring Security with interview questions covering CSRF attacks, CORS, Same-Origin Policy, preflight requests, CSRF tokens, @CrossOrigin, CorsConfigurationSource, and production security best practices.


Introduction

Two of the most frequently confused security concepts in web development are

  • CSRF (Cross-Site Request Forgery)
  • CORS (Cross-Origin Resource Sharing)

Although both involve browsers and HTTP requests, they solve completely different security problems.

Enterprise applications must correctly configure both to build secure systems.

Examples

  • Internet Banking
  • Insurance Portals
  • Healthcare Systems
  • E-Commerce
  • Government Applications

Spring Security provides built-in support for both CSRF protection and CORS configuration.


Browser Security Architecture

flowchart LR

Browser --> SameOriginPolicy

SameOriginPolicy --> CORS

Browser --> CSRFProtection

CSRFProtection --> SpringSecurity

SpringSecurity --> Application

Q1. What is CSRF?

Answer

CSRF stands for Cross-Site Request Forgery.

It is an attack where a malicious website tricks an authenticated user into performing an unwanted action on another website.

Example

A user logs into an online banking application.

Without logging out, the user visits a malicious website.

That site silently submits

POST /transfer

using the user's existing session cookie.

The bank believes the request came from the legitimate user.


Q2. How does CSRF work?

CSRF Attack Flow

sequenceDiagram
User->>Bank: Login
Bank-->>Browser: Session Cookie
User->>MaliciousSite: Visit
MaliciousSite->>Bank: Hidden POST Request
Browser->>Bank: Session Cookie Sent Automatically
Bank-->>MaliciousSite: Request Processed

Because browsers automatically send cookies,

the server cannot distinguish between legitimate and forged requests without CSRF protection.


Q3. How does Spring Security prevent CSRF?

Spring Security generates a unique CSRF Token.

Workflow

  1. Token generated.
  2. Token stored in session.
  3. Client sends token with every modifying request.
  4. Server validates token.
  5. Invalid token → Request rejected.

Example

X-CSRF-TOKEN

Q4. When should CSRF be enabled?

CSRF should remain enabled for

  • Session-based applications
  • Traditional web applications
  • Server-rendered pages
  • Form submissions

CSRF is typically disabled for stateless REST APIs using JWT.

Example

http
    .csrf(csrf -> csrf.disable());

Only disable CSRF when the application is truly stateless.


Q5. What is CORS?

CORS stands for Cross-Origin Resource Sharing.

It allows browsers to access resources hosted on different origins.

Example

Frontend

https://app.bank.com

Backend

https://api.bank.com

Without CORS configuration,

the browser blocks the request.


Q6. What is Same-Origin Policy?

The Same-Origin Policy is a browser security mechanism.

An origin consists of

  • Protocol
  • Host
  • Port

Example

URL Same Origin?
https://app.bank.com
https://api.bank.com
http://app.bank.com
https://app.bank.com:8080

Different origins require CORS permission.


Q7. What is a Preflight Request?

For certain cross-origin requests,

the browser first sends

OPTIONS

to verify whether the server allows the request.

The server responds with headers such as

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers

Only after approval does the browser send the actual request.

Preflight Flow

sequenceDiagram
Browser->>Server: OPTIONS
Server-->>Browser: Allow
Browser->>Server: Actual Request
Server-->>Browser: Response

Q8. How do you configure CORS in Spring Security?

Example

@Bean
CorsConfigurationSource
corsConfigurationSource() {

    CorsConfiguration config =
            new CorsConfiguration();

    config.setAllowedOrigins(
            List.of("https://app.bank.com"));

    config.setAllowedMethods(
            List.of("GET","POST"));

    return source;

}

Spring Security integrates this configuration into the Security Filter Chain.


Q9. CSRF vs CORS

CSRF CORS
Prevents forged requests Allows cross-origin requests
Security protection Browser access control
Uses CSRF Token Uses HTTP headers
Session-based concern Cross-origin concern
Protects authenticated users Controls browser access

They solve different problems and are not substitutes for one another.


Q10. CSRF & CORS Best Practices

Keep CSRF Enabled for Session-Based Applications

Protect form submissions.


Disable CSRF for Stateless JWT APIs

Only when sessions are not used.


Never Use Wildcard Origins in Production

Avoid

*

Specify trusted origins instead.


Restrict HTTP Methods

Allow only required methods.


Enable HTTPS

Protect tokens and credentials.


Banking Example

flowchart TD

Browser --> CORSValidation

CORSValidation --> CSRFValidation

CSRFValidation --> SecurityFilterChain

SecurityFilterChain --> PaymentController

PaymentController --> PaymentService

Both CORS and CSRF checks execute before business logic.


Common Interview Questions

  • What is CSRF?
  • How does a CSRF attack work?
  • How does Spring Security prevent CSRF?
  • When should CSRF be disabled?
  • What is CORS?
  • What is Same-Origin Policy?
  • What is a Preflight Request?
  • How do you configure CORS?
  • CSRF vs CORS?
  • Best practices?

Quick Revision

Topic Summary
CSRF Prevents forged requests
CSRF Token Validates modifying requests
CORS Allows cross-origin access
Same-Origin Policy Browser security restriction
OPTIONS Preflight request
Access-Control-Allow-Origin Allowed origin
JWT API Usually disables CSRF
Session App Enables CSRF
HTTPS Secure transport
Trusted Origins Production recommendation

Complete Browser Request Lifecycle

sequenceDiagram
Browser->>Server: HTTP Request
Server->>CORSFilter: Validate Origin
CORSFilter-->>Server: Allowed
Server->>CsrfFilter: Validate CSRF Token
CsrfFilter-->>Server: Valid
Server->>Controller: Continue
Controller-->>Browser: HTTP Response

Production Example – Banking Payment Portal

A banking portal consists of

Frontend

https://bank-ui.com

Backend

https://api.bank.com

Workflow

  1. Customer logs into the banking portal.
  2. Browser stores the session cookie.
  3. Frontend calls the payment API.
  4. Browser sends a CORS preflight request.
  5. Spring Security verifies the allowed origin.
  6. Browser sends the actual request.
  7. Spring Security validates the CSRF token.
  8. Payment request reaches the controller.
http
    .cors(Customizer.withDefaults())
    .csrf(csrf ->
        csrf.disable()
    );

Note: The above configuration is appropriate only for stateless JWT-based REST APIs. For session-based web applications, CSRF protection should remain enabled.

flowchart LR

ReactApplication --> Browser

Browser --> OPTIONS

OPTIONS --> CorsFilter

CorsFilter --> JwtAuthentication

JwtAuthentication --> PaymentController

PaymentController --> PaymentService

PaymentService --> PostgreSQL

CSRF Enabled vs Disabled

Application Type CSRF
Traditional Spring MVC (Session) ✅ Enable
Thymeleaf Forms ✅ Enable
Banking Web Portal ✅ Enable
REST API with JWT ❌ Usually Disable
Microservices ❌ Usually Disable
Mobile API ❌ Usually Disable

@CrossOrigin vs Global CORS Configuration

@CrossOrigin Global Configuration
Applied to individual controllers Applied application-wide
Good for small projects Recommended for enterprise systems
Easy to configure Centralized management
Harder to maintain at scale Consistent policy enforcement

Example

@CrossOrigin(
    origins = "https://app.bank.com"
)
@RestController
public class PaymentController {

}

CORS Response Headers

Header Purpose
Access-Control-Allow-Origin Allowed origins
Access-Control-Allow-Methods Allowed HTTP methods
Access-Control-Allow-Headers Allowed request headers
Access-Control-Allow-Credentials Allow cookies/credentials
Access-Control-Max-Age Cache preflight response

Enterprise Security Flow

flowchart TD

Browser --> CORSFilter

CORSFilter --> SecurityFilterChain

SecurityFilterChain --> JwtAuthenticationFilter

JwtAuthenticationFilter --> AuthorizationFilter

AuthorizationFilter --> Controller

Controller --> BusinessService

Key Takeaways

  • CSRF (Cross-Site Request Forgery) protects authenticated users from malicious websites that attempt to perform unauthorized actions using existing browser sessions.
  • CORS (Cross-Origin Resource Sharing) controls whether browsers are allowed to make requests across different origins.
  • Spring Security protects session-based applications using CSRF tokens, which are validated for state-changing requests.
  • Stateless REST APIs secured with JWT typically disable CSRF because authentication is not based on browser-managed sessions.
  • Browsers enforce the Same-Origin Policy, and cross-origin requests require explicit CORS configuration.
  • Browsers send an OPTIONS preflight request before certain cross-origin requests to verify that the server permits the operation.
  • Enterprise applications should avoid wildcard origins, allow only trusted domains, restrict HTTP methods, and always use HTTPS.
  • Understanding the distinction between CSRF and CORS is essential for building secure Spring Boot web applications and REST APIs.