CORS, CSRF, and Secure Headers in Spring Boot


Table of Contents

  1. Introduction
  2. What is CORS?
    • Why CORS Exists
    • Configuring CORS in Spring Boot
  3. What is CSRF?
    • CSRF Explained
    • CSRF in State vs Stateless Applications
    • Disabling or Enabling CSRF in Spring Boot
  4. Secure HTTP Headers
    • Why Headers Matter
    • Using Spring Security Headers
  5. Best Practices for API Security
  6. Summary

1. Introduction

When securing a Spring Boot application—especially one exposed over HTTP or HTTPS—it’s crucial to handle CORS, CSRF, and security headers properly. These are often overlooked but form the first line of defense against attacks like cross-site scripting (XSS), cross-site request forgery, clickjacking, and more.


2. What is CORS? (Cross-Origin Resource Sharing)

CORS is a browser mechanism that blocks requests from one origin to another unless explicitly allowed by the server.

Why CORS Exists

Say your frontend (React, Angular) is running on http://localhost:3000 and your backend is on http://localhost:8080. This is considered cross-origin. Browsers block such requests unless the backend says, “I trust this origin.”

Configuring CORS in Spring Boot

There are multiple ways to enable CORS:

At Controller Level

javaCopyEdit@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class MyController {
    // endpoints
}

Globally via WebMvcConfigurer

javaCopyEdit@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("http://localhost:3000")
            .allowedMethods("GET", "POST", "PUT", "DELETE")
            .allowedHeaders("*")
            .allowCredentials(true);
    }
}

With Spring Security

javaCopyEdit@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.cors(Customizer.withDefaults());
    return http.build();
}

And define a CorsConfigurationSource bean if you need fine control.


3. What is CSRF? (Cross-Site Request Forgery)

CSRF Explained

CSRF is an attack where a malicious site tricks a user’s browser into sending unwanted requests to your site, exploiting authenticated sessions.

CSRF in State vs Stateless Applications

  • Stateful Apps (with Sessions): CSRF is a real threat.
  • Stateless REST APIs: Usually CSRF protection is disabled because JWT tokens or other mechanisms are used, and no session is maintained.

Disabling CSRF in Spring Boot

javaCopyEdithttp.csrf().disable();

This is typical in JWT-based authentication scenarios.

Enabling CSRF (If Needed)

For form-based login:

javaCopyEdithttp.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

This stores a CSRF token in a cookie and expects it in a header with every request.


4. Secure HTTP Headers

Headers can protect your app from various attacks:

Common Secure Headers

HeaderPurpose
X-Content-Type-OptionsPrevents MIME type sniffing
X-Frame-OptionsPrevents clickjacking
Strict-Transport-SecurityForces HTTPS
X-XSS-ProtectionEnables basic XSS protection
Content-Security-PolicyRestricts sources for scripts, etc.
Referrer-PolicyControls referrer information

Enable Headers in Spring Security

javaCopyEdithttp.headers()
    .contentTypeOptions()
    .and()
    .frameOptions().deny()
    .and()
    .httpStrictTransportSecurity().includeSubDomains(true).maxAgeInSeconds(31536000)
    .and()
    .xssProtection().block(true);

For CSP (Content Security Policy):

javaCopyEdithttp.headers()
    .contentSecurityPolicy("script-src 'self'; object-src 'none';");

5. Best Practices for API Security

  • Always validate input on both client and server side.
  • Enable CORS only for trusted origins.
  • Disable CSRF if using stateless tokens (JWT, OAuth2), else enable it.
  • Enforce HTTPS and HSTS.
  • Apply security headers for browsers.
  • Rate limit and throttle API requests.
  • Log and monitor for unusual activity.

6. Summary

Security features like CORS, CSRF, and secure HTTP headers may seem minor, but they’re essential to protect your app from common web threats.

  • CORS allows cross-origin requests securely.
  • CSRF should be disabled in token-based APIs but enabled for form-based sessions.
  • Security headers add layers of protection against XSS, clickjacking, and protocol downgrade attacks.