Track 08 · Lesson 3 of 20Attacks and defenses

Track 08 · Attacks and defenses

CORS

Lesson 3 of 20· 8 min

Cross-Origin Resource Sharing lets a server say “these other origins may read my responses”. Your app on app.example.com calls an API on api.example.com, and the browser checks the API’s answer before handing it to your code.

Send a cross-origin request

Change the request and the server’s headers, then send

Your request

Calling page
Method
Body

Server settings on api.example.com

Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers
// running on https://app.example.com
const res = await fetch("https://api.example.com/orders", {
})
const data = await res.json()

    Simple requests and preflights#

    GET, HEAD and POST with only simple headers go straight out; the browser checks the response. Anything else (PUT, DELETE, a JSON body, an Authorization header) triggers a preflight: an OPTIONS request asking permission first. If the preflight fails, the real request is never sent.

    A blocked simple request still reaches your server. If it changed data, that already happened, which is why CORS is not a CSRF defense.

    The misconfiguration that matters#

    Some servers copy whatever Origin arrives into Access-Control-Allow-Origin and add Access-Control-Allow-Credentials: true, to make errors go away. That lets any site read your users’ data with their cookies. Switch the caller to evil.example, pick “Echo the Origin”, and send cookies to see it.

    In a code review

    HighBackend

    CORS that trusts any origin with credentials

    Fix: Allow an explicit list of origins; never reflect arbitrary origins when credentials are allowed.

    0 of 2 checked

    Check yourself

    Why doesn’t switching fetch to no-cors mode fix a CORS error?