HIGH cors wildcardactixjwt tokens

Cors Wildcard in Actix with Jwt Tokens

Cors Wildcard in Actix with Jwt Tokens — how this specific combination creates or exposes the vulnerability

In Actix-web, configuring CORS with a wildcard origin (*) while also requiring and validating JWT tokens can unintentionally expose authenticated routes to cross-origin requests that bypass intended access controls. When allowed_origin is set to *, the CORS middleware allows any external site to make requests to your API. If the frontend sends credentials or custom headers (which is common when using bearer JWT tokens in the Authorization header), browsers will trigger a preflight OPTIONS request. With a wildcard origin and credentials allowed, the preflight can succeed, and the subsequent authenticated request may be processed even when the origin is not explicitly trusted.

JWT tokens are typically transmitted in the Authorization: Bearer <token> header. Because CORS does not block requests based on token validity, a wildcard origin combined with permissive CORS settings can expose endpoints to unauthorized cross-origin use if the token is leaked or if the token is intended for same-origin use only. Attackers can embed the API URL in malicious sites or scripts and rely on the browser to include the token automatically when credentials are allowed. While JWTs themselves are not cookies and are not automatically sent by browsers, JavaScript running on a compromised site can manually add the Authorization header. If CORS permits that origin, the request proceeds, potentially violating the same-origin policy assumptions behind many JWT deployments.

Moreover, some Actix configurations mistakenly allow both wildcard origins and per-route CORS overrides without tightening methods or headers. If the CORS policy is applied globally with allowed_origin: "*" and permissive methods like GET, POST, and OPTIONS, an attacker can craft a cross-origin request that includes sensitive headers. Even though JWT validation occurs after CORS, a lenient preflight can make the endpoint reachable from unexpected origins, increasing the risk of token exfiltration via XSS or accidental exposure in browser devtools. This is especially risky when debugging endpoints or legacy routes that should not be accessible cross-origin.

The combination is problematic because wildcard origins are designed for public, unauthenticated APIs, whereas JWT tokens are typically used for authenticated, same-origin or tightly controlled cross-origin scenarios. Mixing them without explicit origin restrictions and careful header/method scoping creates a mismatch between intended access boundaries and actual runtime behavior. Security checks in middleBrick’s CORS and Authentication categories would flag this as a high-risk finding because it indicates that authenticated endpoints may be accessible from untrusted origins, undermining the protection provided by JWT validation.

Real-world implications include unauthorized cross-origin reads if the API returns sensitive data and the attacker’s page reads the response, or token leakage via Referer headers when navigating from an external site. Even without direct data exfiltration, such misconfigurations violate the principle of least privilege and can be discovered during black-box scans that test CORS headers alongside authentication mechanisms.

Jwt Tokens-Specific Remediation in Actix — concrete code fixes

To remediate CORS issues with JWT tokens in Actix-web, explicitly define allowed origins instead of using *, and tightly scope CORS settings to only the methods and headers required for your authenticated flow. When using JWT bearer tokens in the Authorization header, ensure that allowed_headers includes Authorization and that credentials are not allowed from wildcard origins.

Below is a concrete, working example of secure Actix CORS configuration with JWT validation. This setup uses the actix-cors crate and validates JWTs via a middleware extractor, ensuring that only specified origins can access authenticated routes.

use actix_web::{web, App, HttpServer, HttpResponse, middleware::Logger};
use actix_cors::Cors;
use actix_web::http::header;

async fn protected_route() -> HttpResponse {
    HttpResponse::Ok().body("Authenticated and CORS-safe response")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Define allowed origin(s) explicitly — never use "*" when credentials or custom headers are involved
    let allowed_origin = "https://trusted-frontend.example.com";

    let cors = Cors::default()
        .allowed_origin(&["https://trusted-frontend.example.com"])
        .allowed_methods(vec!["GET", "POST"])
        .allowed_header(header::AUTHORIZATION)
        .allowed_header(header::CONTENT_TYPE)
        .max_age(3600)
        .supports_credentials(); // only if you use cookies/sessions; omit if using only Authorization header

    HttpServer::new(move || {
        App::new()
            .wrap(Logger::default())
            .wrap(cors.clone())
            .route("/api/secure", web::get().to(protected_route))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

If you must support multiple origins (e.g., multiple frontend deployments), enumerate them explicitly and avoid broad patterns:

.allowed_origin("https://app.example.com")
 .allowed_origin("https://staging.example.com")

For JWT validation, implement an extractor or middleware that checks the Authorization header before the handler runs, and ensure that CORS does not short-circuit security by allowing unauthorized origins. Do not combine .allowed_origin("*") with .supports_credentials() or with sensitive headers like Authorization.

In production, also consider tightening CORS to specific paths that require authentication and using route-specific overrides instead of global wildcards. middleBrick’s Pro plan continuous monitoring can help detect accidental wildcard usage in CORS configurations during scheduled scans, and its GitHub Action can fail builds if permissive CORS rules are present in your OpenAPI specs.

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

Is it ever safe to use CORS wildcard with JWT tokens?
Generally no. Wildcard origins (*) should not be used when endpoints require authenticated requests with custom headers like Authorization. If your API serves public, unauthenticated endpoints only, a wildcard can be acceptable, but mixing it with JWT-protected routes undermines origin-based isolation.
How can I verify my Actix CORS and JWT configuration is secure?
Use a scanner that tests CORS headers alongside authentication checks, such as middleBrick. Its Authentication and CORS checks flag wildcard origins with sensitive headers, and its CLI can be integrated into scripts to validate configurations against expected policies.