Troubleshooting CORS Configuration Issues in Spring Cloud Gateway

Abstract: Resolve browser preflight failures and missing Access-Control-Allow-Origin headers in Spring Cloud Gateway by configuring CorsWebFilter or global CorsConfigurationSource.

Created: 2026-07-30 by

Resolving CORS issues in Spring Cloud Gateway requires configuring the built-in CorsWebFilter or defining a global CorsConfigurationSource. Misconfigured allowed origins, methods, or headers often result in browser preflight failures. This guide details the precise Java and YAML configurations needed to enable secure cross-origin requests while maintaining gateway security policies.

Understanding the Problem

Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to prevent web pages from making requests to a different domain than the one that served the web page. When using Spring Cloud Gateway as an API gateway, it sits between your frontend application and backend microservices. If the gateway does not explicitly handle CORS headers, the browser will block the response, resulting in errors such as "No 'Access-Control-Allow-Origin' header is present on the requested resource."

The complexity arises because Spring Cloud Gateway is reactive and non-blocking, unlike traditional Spring MVC applications. Standard annotations like @CrossOrigin do not work directly on gateway routes. Instead, you must configure CORS at the gateway level or within the underlying WebFlux infrastructure. Many developers struggle with this distinction, leading to persistent configuration errors that are difficult to debug without understanding the request lifecycle.

Configuring Global CORS Settings

The most common and effective way to handle CORS in Spring Cloud Gateway is by defining a global CorsConfigurationSource. This approach ensures that all incoming requests passing through the gateway receive the appropriate CORS headers before being routed to downstream services. You can achieve this by creating a bean that defines the allowed origins, methods, and headers.

To implement this, create a configuration class annotated with @Configuration. Inside this class, define a bean of type CorsConfigurationSource. Within the bean definition, instantiate a CorsConfiguration object and set the properties for allowed origins, methods, and credentials. For example, if your frontend is hosted on http://localhost:3000, you should add this URL to the list of allowed origins. It is crucial to avoid using * for allowed origins when dealing with sensitive data or cookies, as modern browsers reject wildcard origins with credentials.

@Bean
public CorsWebFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://localhost:3000");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    
    return new CorsWebFilter(source);
}

This code creates a filter that applies the CORS configuration to all paths (/**). The setAllowCredentials(true) method is essential if your application uses session cookies or authentication tokens. Without this setting, the browser will ignore the CORS headers even if they are present. Additionally, setting allowed headers and methods to * allows flexibility for various HTTP verbs and custom headers, which is typical in RESTful APIs.

Route-Specific CORS Configuration

In some scenarios, you may need different CORS policies for different routes. For instance, public endpoints might allow any origin, while authenticated endpoints restrict access to specific domains. Spring Cloud Gateway allows you to apply CORS configurations per route using the filters section in your application.yml or application.properties file.

However, route-specific CORS filtering in Spring Cloud Gateway is less straightforward than global filtering. A more robust approach is to use a custom filter or rely on the global configuration combined with additional security constraints. If you must use YAML-based configuration, you can define a CorsConfiguration bean and reference it in the route definition, but this often requires additional setup to ensure the filter chain executes correctly.

For most applications, a global configuration is sufficient and easier to maintain. If you find yourself needing granular control, consider implementing a custom GatewayFilterFactory that handles CORS logic dynamically based on the request path or headers. This provides maximum flexibility but adds complexity to your codebase. Always test these configurations thoroughly using tools like Postman or curl to verify that preflight OPTIONS requests are handled correctly.

Debugging Common Issues

Even with correct configuration, CORS issues can persist due to caching, network proxies, or incorrect header values. One common mistake is forgetting that the browser sends a preflight OPTIONS request before the actual HTTP request. Your gateway must respond to these OPTIONS requests with the appropriate 204 No Content status and CORS headers. If the gateway returns an error or redirects the OPTIONS request, the browser will abort the subsequent request.

Another issue is mismatched origin strings. Browsers perform strict string matching for origins. If your frontend is at http://localhost:3000 and your gateway configuration lists https://localhost:3000, the request will be blocked. Ensure that the protocol, domain, and port match exactly. Also, check if your development environment uses IP addresses instead of localhost, as http://192.168.1.5:3000 is considered a different origin from http://localhost:3000.

If you encounter issues, enable DEBUG logging for org.springframework.web.cors to see detailed information about how the CORS configuration is being evaluated. This log output can reveal whether the filter is being invoked and which rules are failing. Additionally, inspect the network tab in your browser's developer tools to verify that the preflight request is sent and what headers are included in the response.

Integrating with Security

When integrating Spring Cloud Gateway with Spring Security, CORS configuration must be compatible with the security filter chain. Spring Security has its own CORS configuration that can override or conflict with the gateway's CORS settings. To resolve this, ensure that the CORS configuration in Spring Security aligns with the gateway's configuration. You can disable Spring Security's default CORS handling if the gateway manages it entirely.

In your security configuration, you can explicitly set the CORS policy to match the gateway's settings. This prevents conflicts where Spring Security blocks a request before the gateway's CORS filter can add the necessary headers. By coordinating these configurations, you ensure a seamless experience for cross-origin requests while maintaining robust security controls.

For related insights on managing microservice interactions, you might find React Client Headers Are Missing in the Server Spring Boot helpful for debugging header propagation issues.

Frequently Asked Questions

Why is my preflight OPTIONS request failing?

Preflight requests fail when the gateway does not respond with the correct CORS headers or returns an error status code. Ensure that your CORS filter allows the OPTIONS method and responds with a 204 No Content status. Check that the Access-Control-Request-Headers in the preflight request are included in your allowed headers list.

Can I use wildcards for allowed origins?

You can use * for allowed origins only if you do not send credentials like cookies or authorization headers. Modern browsers block wildcard origins when credentials are involved to prevent security vulnerabilities. If you need to support credentials, specify the exact origin URLs in your configuration.

How do I handle multiple origins?

To handle multiple origins, call addAllowedOrigin() for each URL in your CORS configuration. Avoid using a comma-separated string, as this is treated as a single literal origin. Dynamically determining allowed origins based on request headers requires a custom filter implementation rather than static configuration.

Does Spring Cloud Gateway cache CORS responses?

Spring Cloud Gateway itself does not cache CORS headers, but browsers may cache preflight responses. The browser determines the cache duration based on the Access-Control-Max-Age header. If you change your CORS configuration, you may need to clear your browser cache or wait for the preflight cache to expire to see the updates.

What is the difference between CorsWebFilter and @CrossOrigin?

@CrossOrigin is an annotation used in Spring MVC controllers to handle CORS for specific endpoints, whereas CorsWebFilter is a reactive filter used in Spring WebFlux and Spring Cloud Gateway. Since Spring Cloud Gateway is built on WebFlux, @CrossOrigin is not applicable, and you must use CorsWebFilter or similar reactive filters.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More