HIGH cors wildcardaspnetbearer tokens

Cors Wildcard in Aspnet with Bearer Tokens

Cors Wildcard in Aspnet with Bearer Tokens — how this specific combination creates or exposes the vulnerability

In ASP.NET, a CORS wildcard policy that allows any origin (origins: "*") can inadvertently expose authenticated routes that rely on Bearer Tokens when the wildcard is combined with credentials-enabled CORS requests. When WithCredentials() is enabled on the client and the server sets AllowAnyOrigin(), browsers treat the response as accessible to the calling origin, even though the request includes an Authorization header with a Bearer Token. This creates a bypass scenario where a malicious frontend served from any origin can make authenticated calls on behalf of the user, violating the same-origin policy intent for bearer-based authentication.

More specifically, CORS is a browser-enforced mechanism; it does not prevent direct HTTP calls (e.g., via curl or Postman). The risk is realized in the browser context: a compromised or malicious site can initiate cross-origin AJAX/fetch requests with credentials: 'include', and if the server responds with Access-Control-Allow-Origin: * and does not reflect the requesting origin, the response is delivered to the attacker’s JavaScript. Because Bearer Tokens are often stored in JavaScript-accessible locations (e.g., memory or insecure storage), this enables token exfiltration or unauthorized API actions via the victim’s session.

ASP.NET Core’s CORS configuration can unintentionally allow this when developers use app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()). The combination of AllowAnyOrigin() and AllowCredentials() is explicitly disallowed by CORS RFCs and results in the browser omitting credentials from the response, but many implementations inspect only whether the request succeeds, missing that authenticated responses are not delivered to the frontend. Attackers leverage this misconfiguration for cross-origin token misuse patterns, where the token remains valid but the UI is tricked into making calls under a different origin.

Consider an API that uses JWT Bearer Tokens issued at login and stored in sessionStorage. If the API’s CORS policy uses a wildcard origin with credentials allowed, a phishing site can load a script that calls the API with the user’s token via a preflighted request. Even if the server rejects the preflight due to credential rules, inconsistent middleware ordering or per-endpoint overrides may permit the wildcard to apply. This misalignment between authentication (Bearer) and CORS validation leads to authorization bypasses categorized under BOLA/IDOR and Authentication failures in middleBrick scans, where unauthenticated scanning detects exposed endpoints that should require a valid token.

Real-world exploit patterns mirror known issues such as CVE-classifications around token leakage via cross-origin contexts. The vulnerability is not in Bearer Tokens themselves but in how CORS rules interact with them. Proper validation requires specifying exact origins for credentialed requests and ensuring that token validation and CORS evaluation are aligned in the middleware pipeline, preventing wildcard origins from coexisting with permissive credentials settings.

Bearer Tokens-Specific Remediation in Aspnet — concrete code fixes

Remediation centers on tightening CORS policy to avoid wildcards when credentials are involved and explicitly defining allowed origins for Bearer Token–protected endpoints. In ASP.NET Core, replace AllowAnyOrigin() with WithOrigins("https://trusted.example.com") when using AllowCredentials(). This ensures that only known frontends can make authenticated requests, mitigating cross-origin token misuse while preserving legitimate browser-based authorization flows.

Additionally, configure CORS at the endpoint or policy level to scope token-requiring routes separately from public routes. Use policy-based CORS to enforce that only authenticated paths validate Bearer Tokens and apply strict origin rules, while public endpoints can remain more permissive if needed. Always set WithExposedHeaders carefully to avoid leaking sensitive information across origins.

Secure CORS Configuration Example with Bearer Tokens

// Program.cs or Startup.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer(options =>
    {
        options.Authority = "https://auth.example.com";
        options.Audience = "api1";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true
        };
    });

builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
        builder =>
        {
            builder.WithOrigins("https://app.trusted.example.com")
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .AllowCredentials();
        });
});

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("CorsPolicy");

app.MapControllers();
app.Run();

On the client, ensure that credentials are included only for trusted origins and that tokens are handled securely. For fetch requests using Bearer Tokens:

fetch('https://api.example.com/values', {
  method: 'GET',
  credentials: 'include',
  headers: {
    'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
  }
}).then(response => response.json())
  .then(data => console.log(data));

For middleware ordering, always place UseAuthentication and UseAuthorization before UseCors to ensure that token validation occurs before CORS evaluation. This sequence prevents scenarios where CORS short-circuits the pipeline and allows unauthorized origins to pass through due to misconfigured precedence.

In continuous monitoring setups described in middleBrick Pro plans, configure regular scans against credentialed endpoints to detect regressions where CORS rules might be broadened inadvertently during deployments. The GitHub Action can enforce a minimum security score by failing builds if a scan identifies a wildcard origin with credentials enabled, providing automated guardrails without altering remediation logic.

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

Why does AllowAnyOrigin with AllowCredentials weaken Bearer Token protection?
Because AllowAnyOrigin instructs the browser to accept responses from any origin, which conflicts with credentialed requests per CORS specifications. Browsers suppress the response from reaching frontend JavaScript when this combination is used, but inconsistent implementations or per-endpoint overrides may expose authenticated responses to malicious origins, enabling token misuse via cross-origin requests.
Can I use wildcards for public endpoints that still require Bearer Tokens?
No. Wildcard origins must not be used with AllowCredentials. For public endpoints that validate Bearer Tokens, either omit credentials in CORS policy or define explicit origins. Tokens should be validated server-side regardless of CORS, but CORS misconfigurations can create browser-side exposure that leads to unauthorized cross-origin usage.