HIGH cors wildcardspring bootapi keys

Cors Wildcard in Spring Boot with Api Keys

Cors Wildcard in Spring Boot with Api Keys — how this specific combination creates or exposes the vulnerability

A CORS wildcard in Spring Boot combined with API key authentication creates a misconfiguration that can unintentionally expose protected endpoints to unauthorized origins. When allowedOrigins("*") is set while API keys are used for authorization, browsers apply CORS rules independently of authentication. For credentials and certain headers, browsers require explicit origins; a wildcard is not sufficient for requests that include authorization headers, causing preflights to fail for legitimate clients.

More critically, a wildcard can be paired with permissive gateway or proxy configurations that forward API keys via headers. If the backend trusts the presence of an API key but CORS allows any origin, an attacker can craft a web page hosted on any domain to invoke the endpoint using the victim’s API key (if the key is embedded or leaked). This does not bypass the API key check, but it exposes key usage patterns and can facilitate abuse if the key is static or shared across services. In addition, if the API key is accidentally reflected in responses or error messages, a wildcard CORS policy enables exfiltration to attacker-controlled domains via JavaScript, turning a secret key into a data exposure vector.

Spring Boot’s CORS configuration should never use a wildcard when the request includes credentials or custom headers like API keys. Instead, specify exact origins and ensure the configuration aligns with authentication mechanisms. The combination of permissive CORS and bearer-like secrets (API keys) violates the principle of least privilege and can lead to information leakage or unauthorized integrations.

During scanning, middleBrick checks for CORS wildcard patterns in Spring Boot applications and flags insecure origins alongside authentication methods. One of the 12 security checks, Property Authorization, evaluates whether authorization mechanisms are correctly tied to CORS policies, while Data Exposure identifies potential leakage when wildcard origins are present. These findings include remediation guidance to replace wildcards with explicit origins and to validate that API keys are not transmitted to untrusted domains.

Api Keys-Specific Remediation in Spring Boot — concrete code fixes

To remediate CORS issues with API keys in Spring Boot, configure CORS at the controller or global level using exact origins and ensure API key validation remains intact. Below are two approaches with code examples.

Global CORS configuration with exact origins

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Value("${allowed.origin}")
    private String allowedOrigin;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins(allowedOrigin)
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("Authorization", "X-API-Key", "Content-Type")
                .exposedHeaders("X-API-Key")
                .allowCredentials(false);
    }
}

Set allowed.origin to a specific origin (for example, https://app.example.com) in your application properties. This prevents any origin from making requests on behalf of the API key holder and avoids credentialed wildcard issues.

Controller-level CORS with API key validation

@RestController
@RequestMapping("/api/v1/users")
@CrossOrigin(origins = "https://trusted.example.com", maxAge = 3600)
public class UserController {

    private final ApiKeyValidator apiKeyValidator;

    public UserController(ApiKeyValidator apiKeyValidator) {
        this.apiKeyValidator = apiKeyValidator;
    }

    @GetMapping("/profile")
    public ResponseEntity getProfile(
            @RequestHeader("X-API-Key") String apiKey,
            @RequestHeader("Origin") String origin) {

        if (!apiKeyValidator.isValid(apiKey)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        UserProfile profile = apiKeyValidator.extractProfile(apiKey);
        return ResponseEntity.ok(profile);
    }
}

In this example, the controller restricts CORS to a single trusted origin and validates the API key on each request. The ApiKeyValidator is a custom service that checks the key against a store and optionally enforces scope or rate limits.

For broader protection, integrate a filter that rejects requests with missing or malformed API keys before CORS processing completes. This ensures that invalid keys do not trigger CORS preflight success, reducing information leakage.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Can I use a wildcard CORS origin if API keys are not exposed to browsers?
No. A wildcard origin with API keys can still enable cross-origin requests to trusted origins if the key is embedded in JavaScript or leaked via error messages. Use exact origins to limit exposure.
Does middleBrick fix CORS or API key issues automatically?
middleBrick detects and reports misconfigurations, including CORS wildcards and API key handling, with remediation guidance. It does not automatically fix or patch configurations.