CORS
CORS is a browser rule that controls which front-end origins may read a response from your API. The server sends Access-Control-Allow-Origin and related headers. It is not an authentication system.
Detailed Explanation
A page at https://app.example that calls https://api.example is a cross-origin request. The browser asks the API whether that origin is allowed. Simple GET/POST may go out and then be hidden from JS if the headers are missing. Other methods and headers trigger a preflight: an OPTIONS request with Access-Control-Request-Method. The API must answer with allow-origin, allow-methods, allow-headers.
Servers set Access-Control-Allow-Origin to a specific origin or, with care, *. * cannot pair with Access-Control-Allow-Credentials: true. If you send cookies, echo the request's Origin only if it is on an allow-list. Reflecting any origin plus credentials is a bug.
Spring's CorsRegistry or a CorsFilter implements this. Nginx can add headers too; do it in one place. A servlet filter that answers OPTIONS with 200 is a common Boot setup.
You reach for CORS when a browser app on another origin consumes your API. You do not need CORS for server-to-server calls or for curl. You do not use CORS as "security": a non-browser client ignores it. Use auth for that.
The cost of * on a cookie API is a browser refusal or, if misconfigured, a data leak to any site. The cost of a missing preflight handler is a failed POST from the SPA and a working Postman, which looks like a front-end bug. The cost of caching preflights too long (Max-Age) is a sticky old allow-list.
Localhost origins (http://localhost:5173) belong on the allow-list in dev only.
Code Examples
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true);
}
}import jakarta.servlet.http.HttpServletResponse;
public class CorsHeaders {
static void allow(HttpServletResponse resp, String origin) {
if ("https://app.example".equals(origin)) {
resp.setHeader("Access-Control-Allow-Origin", origin);
resp.setHeader("Vary", "Origin");
}
}
}Common Gotchas
CORS is not auth
any server-side client can still call you.
Echoing every `Origin` is an open API to hostile pages
Echoing every `Origin` is an open API to hostile pages