Skip to content
All articles
Lessons From the Field#3May 18, 20269 min read

Why "Access-Control-Allow-Origin: *" with Credentials Is a Catastrophic Mistake

Any website on the internet can make authenticated requests as your logged-in users. The catastrophic CORS misconfiguration and the production-ready fix.

Author: SokeBiz Reading time: ~6 minutes Series: Lessons From the Field #3


TL;DR

A CORS policy that allows any origin (*) while also allowing credentials is one of the most dangerous misconfigurations in modern web apps. It means any website on the internet can make authenticated requests to your API on behalf of your logged-in users. This article explains why the combination is fatal, shows a real attack, and gives you the production-ready CORS configuration that prevents it.


The Hook

Imagine a logged-in banking administrator. They're authenticated to your admin portal, sitting with a valid session cookie or JWT token. They're checking their email, or browsing a tab in another window.

Meanwhile, an attacker has set up a website - could be a blog, a "free image hosting" site, a malicious ad network. The attacker tricks the admin into visiting the site (a phishing email with a link, a malicious ad, a forum post with an enticing URL).

The attacker's site loads in the admin's browser. JavaScript runs. It silently makes a fetch() call to your admin API:

POST https://portal.acmebank.example.com/api/admin/services/register
Content-Type: application/json

{ "EndPoint": "exfil", "BaseUrl": "http://attacker.com/listener" }

The admin's browser attaches the authentication cookie automatically (because the request is cross-origin to the attacker, but the target is the bank's domain - and the admin is logged in there). The bank's API receives the request, sees a valid session, and processes it.

The attacker just created a malicious service in the bank's database. No phishing of credentials. No session theft. The admin did nothing wrong.

This is what an open CORS policy with credentials enabled makes possible.


Plain-English Explanation

What CORS is, in 30 seconds

Your web browser enforces a security rule called the Same-Origin Policy. A page loaded from https://portal.acmebank.example.com is only allowed to make requests to https://portal.acmebank.example.com. It cannot read data from https://attacker.com or https://evil-bank.com.

This rule is what prevents random websites from reading your email while you're logged into Gmail, or stealing your bank balance while you're logged into your bank's portal.

CORS (Cross-Origin Resource Sharing) is the system that lets servers opt out of the Same-Origin Policy for specific cases. A server can say: "I trust requests from https://partner-site.com, allow them to call my API." The browser checks the server's CORS policy before allowing the cross-origin request.

What goes wrong

When a server's CORS policy says "I trust every origin" (*), the browser stops enforcing Same-Origin Policy for that server. Any website can call the API.

By itself, this is bad. But it's typically mitigated by authentication - the attacker would still need the admin's session cookie, JWT, or API key.

But when CORS is wide open AND the server allows credentials (AllowCredentials()), the browser will:

  • Send the request
  • Attach the user's authentication cookies/headers
  • Let the calling JavaScript read the response

This is the catastrophic combination. It's the difference between "the attacker can ping the API" and "the attacker can act as any logged-in user, in their browser, from any website, with no user interaction beyond visiting a page."

Why this is so common

Three reasons:

  1. Developers think * means "anyone can read my public API." It does - but * should never be combined with credentials, because the browser won't allow it anyway in some cases. Developers sometimes add AllowCredentials() to "make it work" without realizing they've now broken the security model.
  2. CORS errors are frustrating to debug. A common fix pattern is: "CORS is blocking my request, let me just open it up to debug, I'll lock it down later." Later never comes.
  3. Wildcard subdomain mistakes. A developer writes SetIsOriginAllowed(origin => true) thinking they'll restrict it later, intending "allow all subdomains." They never restrict it.

How It Actually Works (Technical)

Using our synthetic ACME Bank Portal (an ASP.NET Core 6.0 sample app), here's the vulnerable CORS configuration:

The vulnerable pattern

// Program.cs - VULNERABLE
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
{
builder
.SetIsOriginAllowed(origin => true) // ← any origin
.AllowAnyMethod() // ← any HTTP method
.AllowAnyHeader() // ← any header
.AllowCredentials(); // ← cookies/auth sent
});
});

// And later:
app.UseCors("AllowOrigin");

What's wrong?

This policy tells the browser: "For requests to my API, allow JavaScript running on any origin to make calls. Send the user's cookies. Send authentication headers. Allow the calling JavaScript to read the response."

In a normal browser Same-Origin Policy world, a request from https://evil-site.com to https://portal.acmebank.example.com would be blocked unless the API says it trusts https://evil-site.com. This CORS policy says: "I trust every origin."

The browser actually catches this - sometimes

Interestingly, the CORS specification specifically forbids the combination of Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true. If the server literally returns *, the browser refuses to send credentials.

But SetIsOriginAllowed(origin => true) is a wildcard that returns the request's Origin header back to the browser, not a literal *. So the server replies with:

Access-Control-Allow-Origin: https://evil-site.com
Access-Control-Allow-Credentials: true

The browser sees a specific origin (not *), sees credentials are allowed, and proceeds with the request, attaching cookies and allowing the response to be read.

This is the bypass. The combination of "any origin allowed" + "credentials allowed" via SetIsOriginAllowed is the dangerous one, and it doesn't trigger the browser's built-in protection.

The attack chain

Here's the full exploit, end-to-end:

Step 1: Attacker hosts a malicious page on https://innocent-blog.com (could be a real blog they've compromised, or a free hosting site).

Step 2: The malicious page contains:

<script>
fetch('https://portal.acmebank.example.com/api/admin/services/register', {
method: 'POST',
credentials: 'include', // ← send cookies
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
EndPoint: 'exfil',
BaseUrl: 'http://attacker.com/listener',
UserName: 'svc',
Password: 'anything'
})
});
</script>

Step 3: Attacker tricks a logged-in admin into visiting the page (phishing email, malicious ad, forum post).

Step 4: The admin's browser sends the request, including their authentication cookie. The bank's API processes it as a legitimate admin action.

Step 5: Attacker now has a registered service pointing at their server. Combined with article #1 (SSRF via proxy), they have a remote-havoc chain.

The admin's browser allows this because the bank's CORS policy explicitly says "any origin can make credentialed requests."

Why XSS would be redundant

Normally, to act as a logged-in user from another origin, the attacker would need to compromise the bank's domain itself (XSS, subdomain takeover, etc.). CORS misconfiguration removes that requirement. The attacker's own site is the origin - and the bank's CORS policy says "I trust your origin."


What It Looks Like in the Wild

[ Innocent-looking blog ] [ Admin's Browser ] [ Bank API ] [ Attacker server ]
| | | |
| Page loads with hidden <script> | | |
|<--------------------------------------| | |
| | | |
| fetch(POST register, credentials) | | |
|-------------------------------------->| | |
| | POST + admin's cookie | |
| |----------------------------->| |
| | | Check CORS policy |
| | | → origin is allowed |
| | | → credentials allowed |
| | | |
| | | Insert malicious row |
| | | |
| | 200 OK + CORS headers | |
| |<-----------------------------| |
| | | |
| Attacker triggers SSRF | | |
|<--------------------------------------| | |
| | GET /Merchant/exfil | |
| |----------------------------->| |
| | | Outbound to attacker |
| | |------------------------->|
| | | |
| | | Receive connection |
| | | from bank's server IP |

The admin didn't enter credentials. The admin didn't click anything. The admin just visited a website while logged in.


How to Protect Yourself / Your Users

1. Restrict CORS to specific known origins

// Program.cs - FIXED
var allowedOrigins = new[] {
"https://portal.acmebank.example.com",
"https://admin.acmebank.example.com"
};

builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigins", builder =>
{
builder
.WithOrigins(allowedOrigins) // ← explicit allowlist
.WithMethods("GET", "POST", "PUT", "DELETE") // ← specific methods
.WithHeaders("Content-Type", "Authorization") // ← specific headers
.AllowCredentials();
});
});

Key rule: WithOrigins(...) takes an explicit list. SetIsOriginAllowed(origin => true) does not.

2. Never combine wildcard origins with credentials

If you absolutely need AllowAnyOrigin(), you cannot use AllowCredentials(). Pick one:

// Public API, no auth, anyone can call
builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
// (no .AllowCredentials())

// Authenticated API, only specific trusted origins
builder.WithOrigins(allowedOrigins).AllowCredentials();

Never both. The browser enforces this in some cases (literal * + credentials), but SetIsOriginAllowed bypasses that protection.

3. Don't use regex-based origin matching for security

Patterns like *.acmebank.example.com are tempting but error-prone. SetIsOriginAllowed does runtime checks but is easy to misconfigure. Use the explicit allowlist.

If you must support subdomains, validate carefully:

builder.SetIsOriginAllowed(origin =>
{
if (Uri.TryCreate(origin, UriKind.Absolute, out var uri))
{
return uri.Host == "acmebank.example.com"
|| uri.Host.EndsWith(".acmebank.example.com");
}
return false;
});

But be careful - EndsWith(".acmebank.example.com") matches evil.acmebank.example.com.attacker.com too. Use proper parsing, not string operations.

4. Separate public and authenticated APIs

Best practice: don't use CORS for your authenticated APIs at all. If a request requires credentials, it should come from your own domain (no CORS needed). CORS exists for legitimate cross-origin cases - like a partner site embedding your widget or your mobile web app calling your API.

For pure first-party apps (admin panel calling its own backend), CORS should be disabled entirely. The browser's Same-Origin Policy is exactly what you want.

5. Validate the Origin server-side as a defense-in-depth

Even with proper CORS, the server should check the Origin header on sensitive operations:

// Reject requests from unexpected origins on state-changing endpoints
if (Request.Method != "GET")
{
var origin = Request.Headers["Origin"].ToString();
if (!allowedOrigins.Contains(origin))
return BadRequest("Origin not allowed");
}

This catches cases where CORS is misconfigured downstream, or where the attacker is using a non-browser client (which doesn't honor CORS but also doesn't have a session cookie to send).

6. Add CSRF tokens for state-changing operations

Even with proper CORS, defense in depth means CSRF tokens on any operation that changes state:

[HttpPost("RegisterService")]
[ValidateAntiForgeryToken] // ← requires matching token in form + cookie
public ActionResult RegisterService(ServiceModel model)

CSRF tokens are request-specific values the server expects, which an attacker's page cannot read from another origin.

7. Use SameSite cookies

Modern browsers default SameSite=Lax on cookies. This means cookies aren't sent on cross-origin POST requests. Make sure your authentication cookies are SameSite=Strict or SameSite=Lax:

// Program.cs
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.SameSite = SameSiteMode.Strict; // ← strongest
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});

This is a belt-and-suspenders defense. Even if CORS is wide open and SameSite is None, the cookie still won't carry the attacker's session in many cases.


Resources & References


That concludes this three-part series on a real attack chain that turned three "minor" issues into a full server compromise. The next series covers another common pattern: hardcoded secrets and how attackers use them. Subscribe to get it in your inbox.

continue reading

Follow on,LinkedIn OR GitHub