JavaWeb Cross-Origin Solutions: CORS Filters, Nginx Proxy & Interview Guide
This comprehensive guide explains browser same-origin policy, compares four cross-origin solutions (CORS, Nginx reverse proxy, frontend dev proxy, JSONP), provides production-ready Spring Boot CORS filters with OPTIONS preflight handling, Spring Cloud Gateway config, dynamic origin whitelists, and covers interview-focused topics like credential handling, security framework conflicts, and WebSocket cross-origin.
Cross-Origin Essence: Browser Same-Origin Policy
Cross-origin is not a backend problem but a browser-enforced security mechanism called the same-origin policy . The policy requires protocol + domain + port to match exactly; any difference causes the browser to intercept the response (note: the request still reaches the server). Server-to-server calls are not restricted.
Four Mainstream Solutions (Ranked by Recommendation)
1. CORS (W3C Standard, Production First Choice)
Principle: Server adds response headers to explicitly tell the browser which origins are allowed.
Spring Boot Three Implementation Ways
1.1 Local Annotation (Quick Test)
@CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true", maxAge = 3600)
@RestController
public class UserController {}1.2 Global Configuration (Recommended, Unified Management)
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600);
}
}1.3 Filter Configuration (Most Flexible, Compatible with Old Versions, Production Recommended)
Core code shown in "Production-Grade Core Code" section.
2. Nginx Reverse Proxy (Production Multi-Service First Choice)
Principle: Nginx acts as a unified entry, proxying both frontend and backend requests to the same domain/port, making them same-origin from the browser perspective.
Nginx Core Configuration
server {
listen 80;
server_name localhost;
# Frontend static resources
location / {
root /usr/share/nginx/html;
index index.html;
}
# Backend API proxy
location /api/ {
proxy_pass http://localhost:9090/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}Advantage: No business code changes, handles cross-origin for all backend services uniformly.
3. Frontend Dev Proxy (Dev Environment Only)
Principle: Frontend framework (Vue/React) built-in proxy server forwards API requests to backend during development, bypassing same-origin policy.
Vue 3 vite.config.js Example
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:9090',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})Note: Only works in development; production must use CORS or Nginx.
4. JSONP (Legacy, Understand Only)
Principle: Uses <script> tag's exemption from same-origin policy, fetching data via callback function.
Limitations:
Only supports GET requests
XSS security risk
Requires special frontend/backend coordination, now essentially obsolete
Solution Comparison
CORS : Server adds authorization headers; low difficulty; supports all HTTP methods; requires backend cooperation; best for single backend service, production preferred.
Nginx Reverse Proxy : Unified entry, same-origin forwarding; medium difficulty; supports all methods; no backend cooperation needed; best for multi-service, microservices.
Frontend Proxy : Dev server forwarding; very low difficulty; supports all methods; no backend cooperation; only for local development.
JSONP : Script tag callback; medium difficulty; only GET; requires backend cooperation; legacy compatibility only, not recommended.
Production-Grade Core Code & Technical Highlights
1. High-Performance CORS Filter (Fixes Spring Default Config Pitfalls)
Technical Highlights:
Handles OPTIONS preflight early, returns directly, avoiding business filter chain (Spring Security, Shiro), boosting performance 30%+.
Resolves Spring default CORS config conflicts with security frameworks causing cross-origin failures.
Strictly validates request origin, avoiding security risks of using *.
@Component
@Order(Ordered.HIGHEST_PRECEDENCE) // Highest priority, executes first
public class ProductionCorsFilter implements Filter {
@Value("${cors.allowed-origins:http://localhost:8080}")
private List<String> allowedOrigins;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 1. Get and validate origin
String origin = req.getHeader("Origin");
if (allowedOrigins.contains(origin)) {
resp.setHeader("Access-Control-Allow-Origin", origin);
resp.setHeader("Access-Control-Allow-Credentials", "true");
}
// 2. Handle OPTIONS preflight (core optimization)
if ("OPTIONS".equals(req.getMethod())) {
resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Token");
resp.setHeader("Access-Control-Max-Age", "3600"); // Cache 1 hour
resp.setStatus(HttpServletResponse.SC_OK);
return; // Direct return, skip subsequent filters
}
// 3. Non-preflight requests continue
chain.doFilter(request, response);
}
}2. Microservice Gateway Unified Cross-Origin (Spring Cloud Gateway)
Technical Highlights:
Gateway layer handles cross-origin for all microservices, avoiding duplicate config per service.
Supports per-route granular cross-origin rules.
Solves cross-origin header loss after gateway forwarding.
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]': # Match all routes
allowed-origins:
- "http://localhost:8080"
- "https://www.example.com"
allowed-methods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
allow-credentials: true
max-age: 3600
add-to-simple-url-handler-mapping: true # Fix static resource cross-origin3. Dynamic Allowed Origin Config (Multi-Environment Support)
Technical Highlights:
Manage allowed domain list via config files dynamically, no code change or restart needed.
Supports wildcard subdomains (e.g., *.example.com), flexible for multi-environment.
Production forbids * to ensure security.
// Config class
@ConfigurationProperties(prefix = "cors")
@Component
public class CorsProperties {
private List<String> allowedOrigins = new ArrayList<>();
// getter/setter
}
// application.yml
cors:
allowed-origins:
- "http://localhost:8080"
- "https://dev.example.com"
- "https://*.example.com"Core Technical Challenges & Solutions
OPTIONS Preflight Frequency Causing Performance Drop : Each complex request sends OPTIONS first, doubling response time. Root cause: browser doesn't cache preflight or cache time too short. Solutions: (1) Set Access-Control-Max-Age: 3600 to cache 1 hour; (2) Filter handles OPTIONS early, skipping business chain; (3) Prefer simple requests (avoid custom headers).
Cross-Origin Cookie Failure : Backend receives request but cannot read Cookie, login state lost. Root cause: (1) Backend missing allowCredentials=true; (2) Frontend missing withCredentials=true; (3) Cookie SameSite attribute restriction. Solutions: (1) Enable allowCredentials=true in CORS; (2) Set axios withCredentials: true; (3) Cookie set SameSite=None; Secure (HTTPS only).
Spring Security/Shiro Breaking CORS : CORS configured but still errors, preflight returns 401/403. Root cause: Security framework filter priority higher than CORS filter, intercepting OPTIONS. Solutions: (1) Set CORS filter highest priority; (2) Permit OPTIONS in security framework; (3) Use Spring Security built-in CORS support.
Microservice Architecture CORS Config Conflict : Gateway and microservices both configure CORS, duplicate headers appear. Root cause: Gateway forwards, microservice adds headers again, browser errors. Solutions: (1) Configure CORS only at gateway, disable on microservices; (2) Configure gateway to remove duplicate headers.
WebSocket Cross-Origin : WebSocket connection fails with cross-origin error. Root cause: WebSocket handshake also subject to same-origin policy. Solutions: (1) Configure WebSocket CORS support on backend; (2) Use Nginx reverse proxy for WebSocket.
Third-Party API Cross-Origin : Frontend direct call to third-party API fails. Root cause: Third-party server doesn't allow your domain. Solutions: (1) Backend proxies the call, frontend calls own backend; (2) Ask third-party to whitelist your domain.
Interview Bonus Points (Must-Know)
1. When Does OPTIONS Preflight Trigger?
Request method not GET/POST/HEAD
Request headers contain custom fields (e.g., Token, Authorization)
Content-Type not application/x-www-form-urlencoded, multipart/form-data, or
text/plain2. Why Can't allowCredentials=true Use * ?
W3C standard mandatory rule to prevent security vulnerabilities.
Allowing arbitrary origins with cookies enables CSRF attacks stealing sensitive user data.
3. SameSite Attribute Impact on Cross-Origin Cookies?
SameSite=Lax(default): Only same-site requests carry cookies; cross-site GET requests also excluded. SameSite=None: Allows cross-site cookies, but must also set Secure (HTTPS only).
Summary
Development: Use frontend framework built-in proxy, simple and efficient.
Production: Single service use production-grade CORS filter ; multi-service/microservices use Nginx or gateway unified handling .
JSONP only for awareness, rarely used now.
Focus on preflight performance and cookie carrying issues — most common production pitfalls.
Real Interview Simulation
Scenario Design
Interviewer: Frontend at http://localhost:3000, backend Java at http://localhost:8080. Frontend fetch reports blocked by CORS policy. How to solve? Explain from principle to solution.
Candidate: Cross-origin is browser same-origin policy restriction, not server refusing data. Two directions: face CORS standard (add response headers backend) or bypass same-origin check (reverse proxy, JSONP). Most used in projects: CORS and reverse proxy.
Deep Dive CORS
Interviewer: Which headers exactly, how to add? Assume custom headers and cookies.
Candidate: Core headers: Access-Control-Allow-Origin (specific origin, not * with cookies), Access-Control-Allow-Methods, Access-Control-Allow-Headers (must include custom headers like X-Token, Authorization), Access-Control-Allow-Credentials (true for cookies), Access-Control-Max-Age (cache preflight). Implement global Filter for unified handling.
@WebFilter("/*")
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Token");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "3600");
// Preflight fast return, skip business chain
if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(req, res);
}
}In Spring, @CrossOrigin or WebMvcConfigurer also convenient.
Preflight Conditions & Flow
Interviewer: When is preflight sent? Describe interaction flow.
Candidate: Preflight is browser sending OPTIONS to "scout". Triggers when: method not GET/HEAD/POST; or POST with Content-Type application/json, text/xml; or custom headers like X-Token. Flow: browser sends OPTIONS → backend returns 200 with allow headers → actual request proceeds. Backend filter sees OPTIONS, returns 200 immediately with headers.
Production Environment Approach
Interviewer: Production approach? Still write cross-origin config in backend code?
Candidate: Production typically uses reverse proxy to eliminate cross-origin , recommend Nginx. Frontend and /api share same domain/port, browser sees same-origin. Config example:
location /api/ {
proxy_pass http://backend-service:8080/;
proxy_set_header Host $host;
}Frontend requests /api/user, Nginx forwards to backend /user, browser sees same-origin. Zero backend code intrusion, also enables load balancing and HTTPS termination, widely used in large companies. Dev uses Vite/Webpack proxy similarly.
JSONP Knowledge
Interviewer: Know JSONP?
Candidate: Uses <script> cross-domain script loading, only GET. Backend returns function call with data as parameter. Spring MVC demo:
@GetMapping("/jsonp")
@ResponseBody
public String jsonp(@RequestParam String callback) {
String json = "{\"name\":\"Interviewer\"}";
return callback + "(" + json + ")";
}Only reads, no POST/PUT, XSS risk, basically unused now, seen in legacy projects.
Quick Comparison & Selection
Interviewer: Quick comparison recommendation?
Candidate: Comparison table:
CORS (Filter/Config) : Standard frontend-backend separation; all request types; low code intrusion (backend adds headers); ⭐⭐⭐⭐⭐
Reverse Proxy (Nginx) : Production high concurrency; all types; zero intrusion (backend unaware); ⭐⭐⭐⭐⭐
Spring Annotation/Global Config : Rapid dev, monolith; all types; low intrusion (framework built-in); ⭐⭐⭐⭐
JSONP : Legacy systems; only GET; high intrusion (both ends change); ⭐
Daily: small projects or dev use Spring @CrossOrigin; scale up use reverse proxy for one-time fix.
withCredentials Follow-up
Interviewer: Frontend sets withCredentials: true, backend注意事项?
Candidate: Two musts: (1) Access-Control-Allow-Credentials = true; (2) Access-Control-Allow-Origin cannot be *, must be explicit domain like https://myapp.com. Otherwise browser rejects response with console warning.
Production-Grade Filter Coding Challenge
Interviewer: Write production-ready CorsFilter with dynamic whitelist, preflight handling, security validation.
Candidate: Production CorsFilter highlights: dynamic origin whitelist validation prevents forged origin bypass; unified preflight handling returns 200 directly; supports credentials and custom headers.
@Component
@WebFilter("/*")
public class CorsFilter implements Filter {
// Production usually pulls from config center, demo uses constant
private static final List<String> ALLOWED_ORIGINS = List.of(
"http://localhost:3000", "https://myapp.com"
);
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String origin = request.getHeader("Origin");
// Dynamic whitelist validation, prevent * security issues
if (origin != null && ALLOWED_ORIGINS.contains(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Credentials", "true");
}
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Token, X-Requested-With");
response.setHeader("Access-Control-Max-Age", "3600");
// Preflight fast return, skip Spring interceptor chain
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(req, res);
}
}Wildcard Subdomain Support
Interviewer: Many domains or wildcard subdomains?
Candidate: Use regex or Ant-style matching, e.g., *.myapp.com. Implementation:
private boolean isOriginAllowed(String origin) {
return ALLOWED_PATTERNS.stream().anyMatch(pattern -
pattern.matcher(origin).matches()
);
}
// Config "https://.*\.myapp\.com"Spring Boot Config with Global + Controller Override
Interviewer: Without Filter, how to configure via Spring Boot with global default and per-controller override?
Candidate: Use WebMvcConfigurer for global default, combine @CrossOrigin for fine-grained control.
Global Config (All Endpoints)
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("http://localhost:*", "https://*.myapp.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}Technical highlight: allowedOriginPatterns supports wildcards with allowCredentials(true); cannot use allowedOrigins("*") directly — Spring's thoughtful encapsulation.
Per-Endpoint Override
@RestController
@RequestMapping("/payment")
@CrossOrigin(origins = "https://payment.myapp.com", maxAge = 1800)
public class PaymentController { ... }Production Nginx Details (WebSocket & Cache)
Interviewer: Independent frontend/backend domains, Nginx config to avoid cross-origin while handling WebSocket and caching?
Candidate: Typical production Nginx config:
server {
listen 443 ssl;
server_name myapp.com;
# Frontend static resources
location / {
root /data/www;
try_files $uri /index.html;
}
# API reverse proxy, eliminates cross-origin
location /api/ {
proxy_pass http://backend_cluster/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
# Static resource cache optimization
location ~* \.(js|css|png|jpg|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}Frontend requests https://myapp.com/api/user, Nginx forwards to backend cluster http://backend_cluster/user, browser sees pure same-origin, no CORS headers needed. WebSocket works, static resources strongly cached — three birds one stone.
Technical Difficulties & Solutions Recap
1. Simple vs Non-Simple Request Distinction : Unaware of preflight triggers causing custom header failures. Solution: Clear non-simple request conditions, filter handles OPTIONS with correct Allow-Headers/Methods.
2. Cookie Cross-Origin : Frontend withCredentials=true still rejected. Solution: Backend must set Allow-Credentials: true, Allow-Origin not *, must specify exact domain.
3. Origin Whitelist Security : Using * or reflecting Origin unchecked risks CSRF. Solution: Dynamically validate request Origin header against configured whitelist (regex supported), only set Allow-Origin on match.
4. Preflight Performance Overhead : Every non-simple request sends OPTIONS, adding latency. Solution: Set Access-Control-Max-Age to cache preflight result, recommend 3600 seconds.
5. Microservice Gateway Unified CORS : Each service configures CORS redundantly, error-prone. Solution: Configure CorsWebFilter at Spring Cloud Gateway/Zuul entry, internal services cross-origin unaware.
6. Reverse Proxy Losing Client Info : Backend can't get real IP, protocol. Solution: Nginx adds X-Forwarded-For, X-Real-IP, Host headers; backend uses ForwardedHeaderFilter to parse.
7. WebSocket Cross-Origin : Handshake also affected by same-origin policy. Solution: Reverse proxy config Upgrade and Connection headers; CORS cannot solve, must use proxy.
8. Multi-Subdomain Dynamic CORS : Need allow multiple subdomains. Solution: Spring allowedOriginPatterns("https://*.example.com") or filter regex match.
9. Spring Security Integration Pitfalls : Security may override or interfere with CORS. Solution: Enable HttpSecurity.cors(), custom CorsConfigurationSource priority higher than filter.
10. Dev Stage Frontend-Backend Separation Cross-Origin : Local dev frequent cross-origin, constant backend config changes. Solution: Frontend dev server proxy (Vite/Webpack) or backend @CrossOrigin quick open.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
