Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท CSRF, CORS and Headers

CORS Configuration with Spring Security

Understand CORS and configure it correctly in Spring Security: same-origin policy, preflight requests, allowed origins, credentials, Vary header and common mistakes.

You build a React app on http://localhost:3000 and an API on http://localhost:8080. The first fetch fails with "blocked by CORS policy". CORS (cross-origin resource sharing) is the most misunderstood feature of web security, and it is often "fixed" in ways that make an application less safe. This lesson explains what it does, how to configure it in Spring Security, and the mistakes to avoid.

The Spring classes are shown read-only; the runnable stand-in re-implements the browser's and the server's decision logic in plain Java.

What CORS is (and is not)

Browsers enforce the same-origin policy: a script from one origin (scheme + host + port) cannot read responses from another origin. CORS is the server's way of relaxing that rule for chosen origins by sending headers such as Access-Control-Allow-Origin.

Important facts:

  • CORS is enforced by browsers. curl or another server ignores it. It does not protect your API from attackers, it protects users' browsers from other sites reading their data.
  • CORS does not stop a request from being sent. A simple cross-site POST still reaches your server; CORS only stops the page from reading the answer (that is what CSRF protection is for).
  • http://localhost:3000 and http://localhost:8080 are different origins because the ports differ.

Simple requests and preflight

For simple requests (GET/HEAD/POST with basic headers) the browser sends the request and checks the response headers. For anything else, such as PUT, DELETE, JSON bodies or an Authorization header, it first sends a preflight: an OPTIONS request asking "would you accept this?"

sequenceDiagram
    participant B as Browser (app.example.com)
    participant S as API (api.example.com)
    B->>S: OPTIONS /orders  Origin, Access-Control-Request-Method: PUT, Request-Headers: authorization
    S-->>B: 200 Allow-Origin, Allow-Methods, Allow-Headers, Max-Age
    B->>S: PUT /orders  Authorization: Bearer ...
    S-->>B: 200 + Allow-Origin

The preflight carries no credentials, so the security filter chain must let it through.

That last point is where Spring Security trips people up: the preflight has no Authorization header, so if the security chain runs before CORS handling, it answers 401 and the browser reports a CORS error. Spring Security's CorsFilter runs first when you enable http.cors(...).

Configuring CORS

Define a CorsConfigurationSource bean and enable it in the chain:

Java
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .cors(Customizer.withDefaults())             // uses the CorsConfigurationSource bean
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
    return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(List.of("https://app.example.com", "http://localhost:3000"));
    config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
    config.setAllowCredentials(false);
    config.setMaxAge(Duration.ofHours(1));

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/api/**", config);
    return source;
}

@CrossOrigin on a controller and WebMvcConfigurer.addCorsMappings also work in plain Spring MVC, but when Spring Security is present, only the filter-based configuration above reliably handles preflight requests for secured endpoints.

A CORS decision engine

The stand-in below does what the server's CORS filter does: compares the Origin with an allow list, answers preflights and builds the response headers. The Vary: Origin header matters: caches must not serve a response meant for one origin to another.

Java Server-side CORS decisions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The credentials rule and other mistakes

If your page sends cookies or HTTP auth (fetch(url, {credentials: "include"})), the response must contain Access-Control-Allow-Credentials: true, and then Access-Control-Allow-Origin may not be *. Browsers refuse the combination. Spring enforces the same: setAllowCredentials(true) together with setAllowedOrigins(List.of("*")) throws an IllegalArgumentException at startup.

Mistake Why it is wrong Better
Reflecting any Origin back with credentials allowed Every website can then read your users' private data Use an explicit allow list
allowedOriginPatterns("*") plus credentials Same as above Narrow patterns such as https://*.example.com
Allowing null origin Sandboxed iframes and local files send it Never allow it
Matching origins with endsWith("example.com") evilexample.com passes Compare full origins
Disabling security instead of fixing CORS Preflights got 401 Enable http.cors() so the CORS filter runs first
Wildcard on an API that uses cookies Combined with credentials, leaks data Keep the list tight

CORS errors in the browser console are sometimes caused by a server error, not by CORS configuration. A 500 or 401 response without CORS headers is displayed as a CORS failure. Check the Network tab and the server log first.

Do you even need CORS?

Often the best fix is not to cross origins at all. Serve the SPA and the API from the same origin (for example behind one reverse proxy with /api forwarded to Spring), or use a dev-server proxy during development. Same-origin requests need no CORS configuration and no preflights.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who enforces CORS?

    The server only sends headers. The browser decides whether the page may read the response.
  2. 2. Why does a preflight request often get 401 when Spring Security is added?

    Enable http.cors() with a CorsConfigurationSource so the CorsFilter answers preflights before authorization.
  3. 3. Which combination is invalid?

    Browsers reject a wildcard origin when credentials are allowed.
  4. 4. Does CORS stop a malicious site from sending a POST to your API?

    Requests are still sent. That is why CSRF tokens or non-cookie authentication are needed.

Summary

  • CORS relaxes the browser's same-origin policy for chosen origins; it is enforced by browsers, not servers.
  • Non-simple requests trigger an OPTIONS preflight without credentials: enable http.cors() so it is answered before authentication.
  • Use an explicit origin allow list; never combine * with credentials; send Vary: Origin.
  • A same-origin deployment or dev proxy avoids CORS entirely.
  • CORS is not a substitute for CSRF protection or authorization.

Next: Security headers and session protection