Spring Boot CORS: letting browser front ends call your API
CORS decides whether JavaScript on another origin may read your API's responses, and most CORS bugs are preflight requests answered by the wrong component. This page explains how browsers apply CORS, then runs @CrossOrigin, a global configuration, the credentials rule, Spring Security's cors() switch and a CorsFilter in front of your own filters.
Contents
What CORS is and why browsers need it
Browsers follow the same-origin policy: JavaScript loaded from one origin may not read responses from another origin. An origin is the combination of scheme, host and port, so https://shop.example.comhttp://shop.example.comhttps://api.example.com
Cross-Origin Resource Sharing (CORS) is the standard way for a server to relax that rule for chosen origins. The browser sends an OriginAccess-Control-Allow-Origin
- Simple requests:
,GET orHEAD with only basic headers and a form or plain-text content type. The browser sends them directly and checks the response headers afterwards.POST - Preflighted requests: anything else, such as
,PUT , a JSON body or anDELETE header. The browser first sends anAuthorization request withOPTIONS andAccess-Control-Request-Method , and sends the real request only if the server's answer allows it.Access-Control-Request-Headers
Two facts follow that explain most confusion. First, CORS is enforced by the browser, not by the server. curl
| Header | Sent on | Meaning |
|---|---|---|
Access-Control-Allow-Origin | Preflight and actual | The origin allowed to read the response |
Access-Control-Allow-Methods | Preflight | Methods allowed for the actual request |
Access-Control-Allow-Headers | Preflight | Request headers the page may send |
Access-Control-Allow-Credentials | Preflight and actual | Whether cookies and HTTP authentication may be sent |
Access-Control-Expose-Headers | Actual | Response headers that JavaScript may read |
Access-Control-Max-Age | Preflight | Seconds the browser may cache the preflight answer |
Spring offers CORS at three levels: @CrossOriginWebMvcConfigurerCorsFilterHttpClientOrigin
@CrossOrigin on a controller method
The quickest way to open one endpoint to one front end is @CrossOrigin
package demo.basics;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class CrossOriginBasics {
@RestController
static class Endpoints {
@GetMapping("/closed/stock")
public String closed() {
return "42 in stock";
}
@CrossOrigin(origins = "https://shop.example.com")
@GetMapping("/open/stock")
public String open() {
return "42 in stock";
}
@CrossOrigin(origins = "https://shop.example.com")
@DeleteMapping("/open/stock")
public String clear() {
return "cleared";
}
}
static HttpClient http = HttpClient.newHttpClient();
static String base;
static void send(String method, String path, String origin, String requestMethod)
throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
.method(method, BodyPublishers.noBody())
.header("Origin", origin);
if (requestMethod != null) {
request.header("Access-Control-Request-Method", requestMethod);
}
HttpResponse<String> r = http.send(request.build(), BodyHandlers.ofString());
System.out.println(method + " " + path + " Origin: " + origin
+ (requestMethod == null ? "" : " Access-Control-Request-Method: "
+ requestMethod));
System.out.println(" -> " + r.statusCode() + " " + r.body());
r.headers().map().forEach((name, values) -> {
if (name.startsWith("access-control") || name.equals("vary")) {
System.out.println(" " + name + ": " + String.join(", ", values));
}
});
}
public static void main(String[] args) throws Exception {
try (var context = new SpringApplicationBuilder(CrossOriginBasics.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=WARN")
.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
base = "http://localhost:" + port;
System.out.println("--- simple requests ---");
send("GET", "/closed/stock", "https://shop.example.com", null);
send("GET", "/open/stock", "https://shop.example.com", null);
send("GET", "/open/stock", "https://evil.example.net", null);
System.out.println("--- preflight requests ---");
send("OPTIONS", "/open/stock", "https://shop.example.com", "DELETE");
send("OPTIONS", "/closed/stock", "https://shop.example.com", "GET");
}
}
}
--- simple requests ---
GET /closed/stock Origin: https://shop.example.com
-> 200 42 in stock
GET /open/stock Origin: https://shop.example.com
-> 200 42 in stock
access-control-allow-origin: https://shop.example.com
vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
GET /open/stock Origin: https://evil.example.net
-> 403 Invalid CORS request
vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
--- preflight requests ---
OPTIONS /open/stock Origin: https://shop.example.com Access-Control-Request-Method: DELETE
-> 200
access-control-allow-methods: DELETE
access-control-allow-origin: https://shop.example.com
access-control-max-age: 1800
vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
OPTIONS /closed/stock Origin: https://shop.example.com Access-Control-Request-Method: GET
-> 200
- The closed endpoint answered 200 with the data, but with no
. The request reached the server and ran; only the browser would refuse to show the result to the page. This is why CORS is no protection against requests with side effects.Access-Control-Allow-Origin - The open endpoint returned
, the exact origin, which lets a browser page on the shop read the response.access-control-allow-origin: https://shop.example.com - From
, Spring answered 403https://evil.example.net and did not run the controller. Spring goes further than the standard here: it rejects requests from origins that are not allowed instead of only leaving out the header.Invalid CORS request - The preflight for
got 200 withDELETE andaccess-control-allow-methods: DELETE . Withaccess-control-max-age: 1800 , the allowed methods default to the methods of the mapping, and the cache time to 30 minutes.@CrossOrigin - The preflight to the closed endpoint got 200 but no CORS headers at all. A browser treats that as a refusal and never sends the real request.
- Every CORS response carried
, which stops caches from serving one origin's answer to another.Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
@CrossOriginorigins
Global configuration with WebMvcConfigurer
Annotations scattered over controllers are hard to review, and the allowed origins usually differ between environments. A single addCorsMappingsexample.com
package demo.global;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
public class GlobalCors implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOriginPatterns("https://*.example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("Authorization", "Content-Type")
.exposedHeaders("X-Total-Count")
.allowCredentials(true)
.maxAge(3600);
registry.addMapping("/legacy/**")
.allowedOrigins("*")
.allowCredentials(true); // not allowed together with "*"
}
@RestController
static class Endpoints {
@GetMapping("/api/orders")
public ResponseEntity<String> orders() {
return ResponseEntity.ok().header("X-Total-Count", "2").body("[1,2]");
}
@PostMapping("/api/orders")
public String create() {
return "created";
}
@GetMapping("/legacy/orders")
public String legacy() {
return "[1,2]";
}
}
static HttpClient http = HttpClient.newHttpClient();
static String base;
static void send(String method, String path, String... headers) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
.method(method, BodyPublishers.noBody());
StringBuilder sent = new StringBuilder();
for (int i = 0; i < headers.length; i += 2) {
request.header(headers[i], headers[i + 1]);
sent.append("\n > ").append(headers[i]).append(": ").append(headers[i + 1]);
}
HttpResponse<String> r = http.send(request.build(), BodyHandlers.ofString());
System.out.println(method + " " + path + sent);
String body = r.statusCode() == 500 ? "(error page)" : r.body();
System.out.println(" -> " + r.statusCode() + " " + body);
r.headers().map().forEach((name, values) -> {
if (name.startsWith("access-control")) {
System.out.println(" " + name + ": " + String.join(", ", values));
}
});
}
public static void main(String[] args) throws Exception {
try (var context = new SpringApplicationBuilder(GlobalCors.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=OFF")
.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
base = "http://localhost:" + port;
send("OPTIONS", "/api/orders", "Origin", "https://admin.example.com",
"Access-Control-Request-Method", "POST",
"Access-Control-Request-Headers", "authorization,content-type");
send("OPTIONS", "/api/orders", "Origin", "https://admin.example.com",
"Access-Control-Request-Method", "POST",
"Access-Control-Request-Headers", "x-debug");
send("OPTIONS", "/api/orders", "Origin", "https://admin.example.com",
"Access-Control-Request-Method", "PATCH");
send("GET", "/api/orders", "Origin", "https://admin.example.com");
send("GET", "/api/orders", "Origin", "https://example.com");
send("GET", "/legacy/orders", "Origin", "https://admin.example.com");
// The exception behind that 500, reproduced outside the server
CorsConfiguration legacy = new CorsConfiguration();
legacy.addAllowedOrigin("*");
legacy.setAllowCredentials(true);
try {
legacy.validateAllowCredentials();
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException: " + e.getMessage());
}
}
}
}
OPTIONS /api/orders
> Origin: https://admin.example.com
> Access-Control-Request-Method: POST
> Access-Control-Request-Headers: authorization,content-type
-> 200
access-control-allow-credentials: true
access-control-allow-headers: authorization, content-type
access-control-allow-methods: GET,POST,PUT,DELETE
access-control-allow-origin: https://admin.example.com
access-control-expose-headers: X-Total-Count
access-control-max-age: 3600
OPTIONS /api/orders
> Origin: https://admin.example.com
> Access-Control-Request-Method: POST
> Access-Control-Request-Headers: x-debug
-> 403 Invalid CORS request
OPTIONS /api/orders
> Origin: https://admin.example.com
> Access-Control-Request-Method: PATCH
-> 403 Invalid CORS request
GET /api/orders
> Origin: https://admin.example.com
-> 200 [1,2]
access-control-allow-credentials: true
access-control-allow-origin: https://admin.example.com
access-control-expose-headers: X-Total-Count
GET /api/orders
> Origin: https://example.com
-> 403 Invalid CORS request
GET /legacy/orders
> Origin: https://admin.example.com
-> 500 (error page)
IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
- The first preflight asked for
withPOST andauthorization , and all were allowed. The answer listed all four allowed methods and repeated the requested headers. Becausecontent-type is set, the allowed origin is the exactallowCredentials(true) , neverhttps://admin.example.com .* matchedallowedOriginPatterns("https://*.example.com") but notadmin.example.com itself, which got 403 on the simplehttps://example.com . Add the bare domain as a second pattern if it needs access.GET- A preflight asking for the header
, and one asking forx-debug , both got 403, because neither is in the configuration.PATCH - The actual
carriedGET . Without it, browser JavaScript can read only a few basic response headers, so a paging header like this one would look empty to the front end.access-control-expose-headers: X-Total-Count - The
mapping combines/legacy/** withallowedOrigins("*") . The application started normally, but the cross-origin request to that path failed with 500. The last line shows the exception behind it, reproduced outside the server.allowCredentials(true)
The rule behind that exception comes from the CORS standard: a response that allows credentials must name one origin, because *allowedOriginPatterns"*"*allowedOriginPatterns("*")
The defaults of addMapping@CrossOriginGETHEADPOSTmanagement.endpoints.web.cors.*
CORS with Spring Security
With Spring Security on the classpath, every request passes the security filter chain before it reaches Spring MVC. A preflight carries no credentials, because the browser sends them only with the real request. This program runs the same secured API twice, without and with http.cors()
package demo.security;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.Base64;
import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@SpringBootApplication
public class SecurityCors {
@Bean
SecurityFilterChain api(HttpSecurity http, Environment env) throws Exception {
http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
if (env.getProperty("cors-in-security", Boolean.class, false)) {
http.cors(Customizer.withDefaults()); // uses the CorsConfigurationSource bean
}
return http.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://shop.example.com"));
config.setAllowedMethods(List.of("GET", "POST"));
config.setAllowedHeaders(List.of("Authorization"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
@Bean
UserDetailsService users() {
return new InMemoryUserDetailsManager(User.withUsername("ana")
.password("{noop}pw").roles("USER").build());
}
@RestController
static class Endpoints {
@CrossOrigin(origins = "https://shop.example.com") // read by Spring MVC only
@GetMapping("/api/profile")
public String profile() {
return "profile of ana";
}
}
static void send(String base, String method, String... headers) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + "/api/profile"))
.method(method, BodyPublishers.noBody())
.header("Origin", "https://shop.example.com");
for (int i = 0; i < headers.length; i += 2) {
request.header(headers[i], headers[i + 1]);
}
HttpResponse<String> r = HttpClient.newHttpClient()
.send(request.build(), BodyHandlers.ofString());
System.out.println(" " + method + (method.equals("OPTIONS") ? " (preflight)" : "")
+ " -> " + r.statusCode() + ", Access-Control-Allow-Origin: "
+ r.headers().firstValue("Access-Control-Allow-Origin").orElse("(none)"));
}
static void run(boolean corsInSecurity) throws Exception {
System.out.println("http.cors() " + (corsInSecurity ? "enabled" : "not called") + ":");
try (var context = new SpringApplicationBuilder(SecurityCors.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=OFF", "cors-in-security=" + corsInSecurity)
.run()) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String base = "http://localhost:" + port;
String basic = "Basic " + Base64.getEncoder().encodeToString("ana:pw".getBytes());
send(base, "OPTIONS", "Access-Control-Request-Method", "GET",
"Access-Control-Request-Headers", "authorization");
send(base, "GET", "Authorization", basic);
}
}
public static void main(String[] args) throws Exception {
run(false);
run(true);
}
}
http.cors() not called:
OPTIONS (preflight) -> 401, Access-Control-Allow-Origin: (none)
GET -> 200, Access-Control-Allow-Origin: https://shop.example.com
http.cors() enabled:
OPTIONS (preflight) -> 200, Access-Control-Allow-Origin: https://shop.example.com
GET -> 200, Access-Control-Allow-Origin: https://shop.example.com
- Without
, the preflight got 401 from Spring Security, with no CORS headers. Spring MVC and itshttp.cors() never saw it. A browser would report a CORS error and never send the real request.@CrossOrigin - The real
with theGET header worked in both runs, which is why this problem does not show up in tests withAuthorization or Postman. Only browsers send preflights.curl - With
, Spring Security added ahttp.cors(Customizer.withDefaults()) near the start of its chain, using theCorsFilter bean. The preflight got 200 with the allowed origin before authentication was checked.CorsConfigurationSource
When there is no CorsConfigurationSourcecors()@CrossOriginaddCorsMappings@CrossOriginspring-boot-starter-security
CorsFilter in front of your own filters
The same problem appears without Spring Security whenever a filter of your own rejects requests that lack credentials. Here an API key filter answers 401 for any request without X-Api-Key@CrossOriginCorsFilter
package demo.corsfilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.OncePerRequestFilter;
@SpringBootApplication
public class CorsFilterFirst {
// An authentication filter written by hand: every request needs an API key
@Bean
FilterRegistrationBean<OncePerRequestFilter> apiKeyFilter() {
OncePerRequestFilter filter = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if (request.getHeader("X-Api-Key") == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
chain.doFilter(request, response);
}
};
FilterRegistrationBean<OncePerRequestFilter> registration =
new FilterRegistrationBean<>(filter);
registration.setOrder(0);
return registration;
}
// Answers CORS before any other filter, including the API key check
@Bean
@ConditionalOnProperty(name = "cors-filter", havingValue = "true")
FilterRegistrationBean<CorsFilter> corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://shop.example.com"));
config.setAllowedMethods(List.of("GET"));
config.setAllowedHeaders(List.of("X-Api-Key"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<CorsFilter> registration =
new FilterRegistrationBean<>(new CorsFilter(source));
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
return registration;
}
@RestController
static class Endpoints {
@CrossOrigin(origins = "https://shop.example.com", allowedHeaders = "X-Api-Key")
@GetMapping("/api/basket")
public String basket() {
return "2 items";
}
}
static void send(String base, String method, String... headers) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + "/api/basket"))
.method(method, BodyPublishers.noBody())
.header("Origin", "https://shop.example.com");
for (int i = 0; i < headers.length; i += 2) {
request.header(headers[i], headers[i + 1]);
}
HttpResponse<String> r = HttpClient.newHttpClient()
.send(request.build(), BodyHandlers.ofString());
System.out.println(" " + method + (method.equals("OPTIONS") ? " (preflight)" : "")
+ " -> " + r.statusCode() + ", Access-Control-Allow-Origin: "
+ r.headers().firstValue("Access-Control-Allow-Origin").orElse("(none)"));
}
static void run(boolean corsFilter) throws Exception {
System.out.println(corsFilter ? "CorsFilter first in the chain:"
: "@CrossOrigin only (Spring MVC):");
try (var context = new SpringApplicationBuilder(CorsFilterFirst.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=OFF", "cors-filter=" + corsFilter)
.run()) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String base = "http://localhost:" + port;
send(base, "OPTIONS", "Access-Control-Request-Method", "GET",
"Access-Control-Request-Headers", "x-api-key");
send(base, "GET", "X-Api-Key", "k-123");
}
}
public static void main(String[] args) throws Exception {
run(false);
run(true);
}
}
@CrossOrigin only (Spring MVC):
OPTIONS (preflight) -> 401, Access-Control-Allow-Origin: (none)
GET -> 200, Access-Control-Allow-Origin: https://shop.example.com
CorsFilter first in the chain:
OPTIONS (preflight) -> 200, Access-Control-Allow-Origin: https://shop.example.com
GET -> 200, Access-Control-Allow-Origin: https://shop.example.com
- With
only, the preflight hit the API key filter first and got 401. The annotation is read by Spring MVC, which comes after all filters.@CrossOrigin - With the
atCorsFilter , the preflight was answered with 200 and the CORS headers.Ordered.HIGHEST_PRECEDENCE ends the chain itself for a valid preflight, so the API key filter never saw it.CorsFilter - The real
, which carries the key, passed both filters in both runs.GET
The same rule applies to PreFlightHttpRequestHandlerCorsUtils.isPreFlightRequest(request)
Common CORS mistakes
- Origins with a path or slash: an origin is only scheme, host and port.
with a trailing slash never matches the browser'shttps://shop.example.com/ header.Origin - Testing without a browser: CORS problems appear only in browsers. Test preflights explicitly, as these programs do, or in the browser's network tab.
- Reading custom response headers: headers such as
orX-Total-Count are invisible to JavaScript until they are listed inLocation .exposedHeaders - CORS as access control: allowing only your own front end does not stop other clients from calling the API. Authentication and CSRF protection do that.
- Proxies and gateways: when a gateway in front of the application also adds CORS headers, responses can end up with two
values, which browsers reject. Configure CORS in one layer.Access-Control-Allow-Origin - Development servers: a front-end dev server on
is a different origin from the API onhttp://localhost:5173 . Allow it only in a development profile, or use the dev server's proxy so that no CORS is needed.http://localhost:8080
Choosing where to configure CORS
| Situation | Use |
|---|---|
| One or two endpoints for one front end | @CrossOrigin(origins = ...) |
| A whole API with one policy | addCorsMappingsWebMvcConfigurer |
| Spring Security in the application | http.cors()CorsConfigurationSource |
| Your own authentication filters or interceptors | CorsFilter |
| Cookies or HTTP authentication across origins | allowCredentials(true)allowedOriginPatterns |
| Many subdomains | allowedOriginPatterns("https://*.example.com") |
| Front end needs a response header | exposedHeaders |
| Fewer preflight round trips | maxAge |
Whatever you choose, configure CORS in one place and make sure it answers preflights before any authentication does. For the filter chain these settings live in, see