Skip to lesson

Configuring CORS in Spring Security

ShopLite's web page on port 3000 cannot call its secured API on port 8080: every call fails in Chrome while curl works. Where do you tell the browser which pages may call the API?

http.cors(Customizer.withDefaults()) and a CorsConfigurationSource bean

A CorsConfigurationSource is a Spring bean that answers one question: for this request path, which CORS rules apply? The usual one maps path patterns such as /api/** to a CorsConfiguration, which holds the allowed origins, methods and headers.

ShopLite keeps its CORS rules in one small class next to SecurityConfig. The first example builds the rules; the second switches them on.

Example 1 · src/main/java/com/shoplite/common/security/CorsConfig.java

Runs in: the shoplite-api Spring Boot project

Java
package com.shoplite.common.security;
import java.util.List;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpHeaders;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.CorsConfigurationSource;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
/** * CORS for browser clients on another origin (the ShopLite web shop, the admin pages). * SecurityConfig turns it on with http.cors(...), so preflights are answered before any login check. */@Configuration@EnableConfigurationProperties(CorsProperties.class)class CorsConfig {
    private static final Logger log = LoggerFactory.getLogger(CorsConfig.class);
    @Bean    CorsConfigurationSource corsConfigurationSource(CorsProperties properties) {        CorsConfiguration api = new CorsConfiguration();        // Exact origins from configuration: never "*", never copied from the request        api.setAllowedOrigins(properties.allowedOrigins());        api.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE"));        api.setAllowedHeaders(List.of(HttpHeaders.AUTHORIZATION, HttpHeaders.CONTENT_TYPE));        // Response headers JavaScript may read besides the basic ones (the URL of a created item)        api.setExposedHeaders(List.of(HttpHeaders.LOCATION));        // The token travels in the Authorization header, not in a cookie: no credentials mode needed        api.setAllowCredentials(false);        api.setMaxAge(properties.maxAge());
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        source.registerCorsConfiguration("/api/**", api);        log.info("CORS allowed origins: {}", properties.allowedOrigins());        return source;    }}
Sample output (startup log, dev profile)
2026-10-16T13:14:03.765+05:30  INFO 30468 --- [shoplite-api] [           main] c.shoplite.common.security.CorsConfig    : CORS allowed origins: [http://localhost:3000]

What this code does

  • One CorsConfiguration holds every rule; registerCorsConfiguration("/api/**", api) applies it to the API only. Actuator and Swagger UI get no CORS headers, because no browser frontend on another origin needs them.
  • The class only builds rules; it is SecurityConfig that switches the filter on. Logging the origins at startup lets you check a deployment from its log in one glance.

Example 2 · src/main/java/com/shoplite/common/security/SecurityConfig.java

Runs in: the shoplite-api Spring Boot project

SecurityConfig.javaJava
package com.shoplite.common.security;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.HttpMethod;import org.springframework.security.config.Customizer;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;import org.springframework.security.web.SecurityFilterChain;
/** * Every security rule of ShopLite lives in this one class. * Rules are checked from top to bottom; the first rule that matches a request decides. */@Configuration@EnableWebSecuritypublic class SecurityConfig {
    private static final String[] API_DOCS = { "/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html" };
    @Bean    SecurityFilterChain securityFilterChain(HttpSecurity http, SecurityProblems problems) throws Exception {        http            // CORS first: answers preflights from allowed origins before any token check            .cors(Customizer.withDefaults())            .authorizeHttpRequests(auth -> auth                .requestMatchers(HttpMethod.POST, "/api/v1/auth/login").permitAll()                .requestMatchers(HttpMethod.GET, "/api/v1/products/**", "/api/v1/categories/**").permitAll()                .requestMatchers(HttpMethod.GET, "/api").permitAll()                .requestMatchers("/actuator/health/**").permitAll()                .requestMatchers(API_DOCS).permitAll()                .requestMatchers("/error").permitAll()                .requestMatchers("/api/v1/me/**").hasRole("CUSTOMER")                .anyRequest().hasRole("ADMIN"))            .oauth2ResourceServer(oauth -> oauth                .jwt(jwt -> jwt.jwtAuthenticationConverter(rolesFromToken()))                .authenticationEntryPoint(problems.unauthorized())                .accessDeniedHandler(problems.forbidden()))            .exceptionHandling(ex -> ex                .authenticationEntryPoint(problems.unauthorized())                .accessDeniedHandler(problems.forbidden()))            .csrf(csrf -> csrf.disable())            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));        return http.build();    }
    /** The token's "roles" claim (["CUSTOMER"]) becomes the authorities ROLE_CUSTOMER, ... */    private static JwtAuthenticationConverter rolesFromToken() {        JwtGrantedAuthoritiesConverter authorities = new JwtGrantedAuthoritiesConverter();        authorities.setAuthoritiesClaimName("roles");        authorities.setAuthorityPrefix("ROLE_");        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();        converter.setJwtGrantedAuthoritiesConverter(authorities);        return converter;    }}
Sample output (preflight for GET /api/v1/me/orders from http://localhost:3000; security headers left out)
HTTP/1.1 200 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE
Access-Control-Allow-Headers: authorization
Access-Control-Expose-Headers: Location
Access-Control-Max-Age: 3600
Content-Length: 0
Date: Fri, 16 Oct 2026 08:05:13 GMT

What this code does

  • .cors(Customizer.withDefaults()) is the only new line. It finds the CorsConfigurationSource bean by type and puts the CorsFilter before the token filter and the authorization rules.
  • The preflight to /api/v1/me/orders, a CUSTOMER-only URL, now gets 200 with the CORS headers and no token at all. The real GET that follows still needs a valid token.
  • SecurityProblems is the one class from the JWT module again: the Roles module split it into an entry point, an access-denied handler and a writer to show each job; with the jobs clear, ShopLite keeps them together in one class with the same answers.

Both parts are needed. A bean without http.cors(...) does nothing in Spring Security 7, and http.cors(...) without rules has nothing to allow.

Without either, the pain is the one from the first lesson: the frontend gets TypeError: Failed to fetch on every call, while curl and Postman work fine. Keeping the bean in its own class makes the access rules and the browser rules easy to find and to test.

Interview angle: "Where do you configure CORS in Spring Boot with Spring Security?" In a CorsConfigurationSource bean, enabled with http.cors(...) in the SecurityFilterChain, so it runs before authentication.

Allowed origins from configuration, per profile

Allowed origins are the exact origins, each a scheme, a host and an optional port, that a CORS configuration lets read the API. ShopLite reads them from shoplite.cors.allowed-origins, so each profile allows only its own frontend.

The next example binds the allowed origins to a validated record, then shows three starts: dev, prod and a typo.

Example 3 · CorsProperties.java and the two profiles

Runs in: the shoplite-api Spring Boot project

CorsProperties.javaJava
package com.shoplite.common.security;
import java.time.Duration;import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.context.properties.bind.DefaultValue;import org.springframework.validation.annotation.Validated;
import jakarta.validation.constraints.Pattern;
/** * Which browser origins may call the API (shoplite.cors.*), set per profile. * Each origin is exact: scheme, host and optional port, with no path and no trailing slash. */@Validated@ConfigurationProperties("shoplite.cors")public record CorsProperties(        @DefaultValue List<@Pattern(regexp = "https?://[a-z0-9.-]+(:[0-9]{1,5})?",                message = "must look like https://shop.example or http://localhost:3000 (no path, no trailing slash, no *)")                String> allowedOrigins,        @DefaultValue("1h") Duration maxAge) {}
/*# src/main/resources/application-dev.properties (your own computer)# CORS: the frontend you run on your own computershoplite.cors.allowed-origins=http://localhost:3000
# src/main/resources/application-prod.properties (the server)# CORS: the real web shop's origin(s), comma-separated, set on the server (the app will not start without it)shoplite.cors.allowed-origins=${CORS_ALLOWED_ORIGINS}*/
Sample output (three starts: dev, prod with the variable set, dev with a trailing-slash typo)
$ java -jar target/shoplite-api-1.0.0.jar
... c.shoplite.common.security.CorsConfig    : CORS allowed origins: [http://localhost:3000]

$ CORS_ALLOWED_ORIGINS=https://shoplite.example,https://admin.shoplite.example java -jar target/shoplite-api-1.0.0.jar --spring.profiles.active=prod
{"log":{"level":"INFO","logger":"com.shoplite.common.security.CorsConfig"}, ... "message":"CORS allowed origins: [https://shoplite.example, https://admin.shoplite.example]"}

$ java -jar target/shoplite-api-1.0.0.jar --shoplite.cors.allowed-origins=http://localhost:3000/
***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target com.shoplite.common.security.CorsProperties failed:

    Property: shoplite.cors.allowedOrigins[0]
    Value: "http://localhost:3000/"
    Reason: must look like https://shop.example or http://localhost:3000 (no path, no trailing slash, no *)


Action:

Update your application's configuration

What this code does

  • @DefaultValue List<...> gives an empty list when a profile sets nothing, which means "no browser origin is allowed". The @Pattern on the element type checks every origin in the list, and @Validated makes Spring run the check at startup.
  • The third start shows the guard working: one extra / and the app refuses to start, naming the property, the value and the rule. The same check stops a prod start where CORS_ALLOWED_ORIGINS was forgotten.

Allowed origins differ by environment: http://localhost:3000 on your laptop, https://shoplite.example on the server. Hard-coding either one means editing code to deploy. The dev profile lists http://localhost:3000; the prod profile reads ${CORS_ALLOWED_ORIGINS}, a comma-separated list that Spring binds to a List<String>. No profile ever allows *.

A @Pattern on the list elements checks each origin at startup: scheme, host and optional port, nothing else. A trailing slash, a path, a missing scheme or * stops the app with "APPLICATION FAILED TO START", and so does a forgotten prod variable, because the unresolved text ${CORS_ALLOWED_ORIGINS} fails the same pattern. A wrong setting is found in seconds at deploy time, not by a customer in the browser.

Fix the error

Fix the origin that stops startup

The app refuses to start. Pick the replacement for the highlighted line.

Round 1 of 2

The origin ends with a slash.

# application-dev.properties
shoplite.cors.allowed-origins=http://localhost:3000/

Error

Property: shoplite.cors.allowedOrigins[0]
Value: "http://localhost:3000/"
Reason: must look like https://shop.example or http://localhost:3000
Spring itself removes one trailing slash from allowed origins, but the check keeps the configuration exact and honest. It also catches the mistakes Spring cannot fix, such as localhost:3000 without http://.

Allowed methods, headers, exposed headers and allowCredentials

setAllowCredentials(true) makes Spring send Access-Control-Allow-Credentials: true, so the browser may send cookies and let the page read the answer. It needs exact origins, never *.

The curl runs below send the login preflight, then a request from an origin that is not on the list.

Example 4 · The login preflight and a request from an unknown origin

Runs in: a terminal, with the ShopLite API (dev profile) running on port 8080

Terminal
curl -i -X OPTIONS http://localhost:8080/api/v1/auth/login \  -H "Origin: http://localhost:3000" \  -H "Access-Control-Request-Method: POST" \  -H "Access-Control-Request-Headers: content-type"curl -i http://localhost:8080/api/v1/products/1 -H "Origin: https://evil.example"
Sample output (Spring Security's Cache-Control, Pragma, Expires and X- headers left out; your Date differs)
HTTP/1.1 200 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE
Access-Control-Allow-Headers: content-type
Access-Control-Expose-Headers: Location
Access-Control-Max-Age: 3600
Content-Length: 0
Date: Fri, 16 Oct 2026 08:05:13 GMT

HTTP/1.1 403 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 08:05:14 GMT

Invalid CORS request

What this code does

  • The login preflight is answered with the allowed methods, the one requested header (content-type), Location as an exposed header and a one-hour Max-Age. There is no Access-Control-Allow-Credentials line, because ShopLite keeps credentials off.
  • For an origin that is not in the list, Spring answers 403 Invalid CORS request with no CORS headers. A browser page on that origin can read nothing; curl without an Origin header still gets the product, because CORS is about browsers.

The settings in CorsConfig, one by one:

  • Allowed origins: the exact list from configuration.
  • Allowed methods: GET, POST, PUT, PATCH, DELETE, what the frontend uses. Allowed headers: Authorization, Content-Type, never *.
  • Exposed headers: Location, so the page can read the URL of a product it just created (201 Created). Max age: 1h.
  • Credentials: false. ShopLite sends its token in the Authorization header and uses no cookies.

Turn credentials on only for cookie-based sign-in, and then only with exact origins; the next lesson shows why.

Why CORS must run inside the security chain

http.cors(Customizer.withDefaults()) adds Spring Security's CorsFilter near the start of the security chain, before any authentication filter. The filter answers a valid preflight itself, which carries no token.

The curl runs below send the same token-less preflight to a lab app: first with CORS only in Spring MVC, then with http.cors(...).

Example 5 · CORS outside the chain: the preflight gets 401

Runs in: the cors-lab Spring Boot project (one chain, two CORS setups), running on port 8080

Terminal
curl -i -X OPTIONS http://localhost:8080/api/v1/me/orders \  -H "Origin: http://localhost:3000" \  -H "Access-Control-Request-Method: GET" \  -H "Access-Control-Request-Headers: authorization"
Sample output (Spring Security's Cache-Control, Pragma, Expires and X- headers left out; your Date differs)
### cors-lab, CORS only in Spring MVC (WebMvcConfigurer), chain without http.cors(...)
HTTP/1.1 401 
WWW-Authenticate: Basic realm="Realm", charset="UTF-8"
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 08:05:22 GMT

{"timestamp":"2026-10-16T08:05:21.916Z","status":401,"error":"Unauthorized","path":"/api/v1/me/orders"}

### cors-lab, the same chain with .cors(Customizer.withDefaults())
HTTP/1.1 200 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE
Access-Control-Allow-Headers: authorization
Access-Control-Expose-Headers: Location
Access-Control-Max-Age: 3600
Content-Length: 0
Date: Fri, 16 Oct 2026 08:05:30 GMT

What this code does

  • In the first run CORS lives only in a WebMvcConfigurer. The security chain answers the token-less preflight with 401 and WWW-Authenticate before Spring MVC can add any CORS header, so Chrome reports Response to preflight request doesn't pass access control check. A CorsConfigurationSource bean without http.cors(...) and a controller with @CrossOrigin gave the same 401 in this lab.
  • In the second run the only change is .cors(Customizer.withDefaults()). The CorsFilter now answers the preflight first, and the 401 disappears without opening any URL to anonymous users.

A preflight carries no token. If authorization runs first, Spring Security sees an anonymous OPTIONS /api/v1/me/orders, the rule hasRole("CUSTOMER") fails and the answer is 401 with no CORS headers. The browser reports a failed preflight and never sends the real request.

The same happens when CORS is set only in Spring MVC, with WebMvcConfigurer.addCorsMappings or @CrossOrigin: the DispatcherServlet runs after the security filters. Public GET calls still work, so the bug is confusing: the product list loads, but login and "My orders" fail. With http.cors(...) the filter also adds Access-Control-Allow-Origin to real responses, 401 and 403 problems included, so the page can read the error body.

Find the bug

Find the wrong CORS setup

Preflights to /api/v1/me/orders get 401. Click the line that is the problem.

This chain tries to "fix" the 401 on preflights. Which line is wrong?

Round 1 of 2
Do not "fix" this by adding .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll(). It hides the 401, but without CORS headers the browser still blocks the call, and it opens OPTIONS on every URL.

A tiny page to see it work end to end

jwebserver is the small static file server that ships with JDK 18 and later. jwebserver -p 3000 serves the current folder at http://localhost:3000, so a page opened that way has the origin of a real frontend dev server.

The page below calls the ShopLite API on port 8080 from a page served on http://localhost:3000.

Text
<!-- index.html, served by: jwebserver -p 3000 --><script>  fetch('http://localhost:8080/api/v1/products/1')    .then(response => response.json())    .then(product => console.log('Product:', product.name, product.price))    .catch(error => console.log('fetch failed ->', error.name + ': ' + error.message));</script>

On JDK 17, python -m http.server 3000 or any other static server does the same job. Open http://localhost:3000 with the API running in the dev profile and the console prints Product: Redmi Note 13 5G 17999. Open the same page as http://127.0.0.1:3000: same file, same server, but a different origin that ShopLite does not allow, so the page prints fetch failed -> TypeError: Failed to fetch with a CORS error above it.

Check the Network tab too. A public GET shows one request. A signed-in call shows an OPTIONS request with status 200 followed by the real request, and within the next hour only the real request (the preflight cache).

Next step

Check your understanding

12 quick questions