tags : Web Authentication, Security, Web Security, Same Origin Policy (SOP)

Cross Origin Request Sharing

What it is and what not

What it is

  • CORS allows to selectively bypass SOP in the browser for network access, loosening our security in the browser, increasing our attack surface area.

What it’s not

  • It’s not a rate limiting mechanism (See API Design)
  • Not an origin based auth thing for your API endpoint. non-browser clients will always be able to access your API endpoint.

How is it implemented?

  • SOP itself is more than just network access as written previously.
  • CORS allows bypassing SOP for
    • cross-domain request read
    • cross-domain cookie send
    • cross-domain extra http methods
  • Happens though an agreement b/w browser and server.

Browser side

  • Same Origin Policy (SOP) does allow limited cross-origin requests
  • For cases where it does not allow
    • It checks access-control headers if to allow reads
    • It uses preflight if sever even allows certain things it’s going to request

How does preflight work?

  • This adds additional latency (this is cached by the browser for access-control-max-age)
  • It’s additional requests, it’s extra monie
  • Send an OPTIONS to figure out what all methods are allowed by the endpoint. It sends the OPTIONS request with these “request” headers.
    Access-Control-Request-Method: POST
    Access-Control-Request-Headers: X-PINGOTHER, Content-Type

Sending cookies in cross-origin requests

Server side

  • It’s HTTP header based
  • Need to configure CORS headers

Access control headers

  • access-control-allow-credentials: If set, cookies are sent by the browser
  • access-control-allow-origin:
    • Origins allowed to read responses
    • * to allow anyone to make requests.
      • allow-credentials must be unset. Because otherwise it means, anyone from any website will be able to make request to your website aswell as send cookies.
      • Eg. If fb.com/secret had * and allow-credentials by mistake, you’d be able to have read access fb.com/secret from any website. This is not allowed.
      • So if * is set, cookies/creds will never be sent.
      • See CSRF
  • access-control-allow-methods: HTTP methods allowed

When use

It’s best to avoid CORS is possible and let Same Origin Policy (SOP) do its job. But in certain cases we can’t avoid doing CORS.

When to use?

  • When providing an API for third parties to consume from a browser (eg. after going through an OAuth process).

When not to use?

  • preflight adds latency, so if we want to cut corners, we do not want to be doing preflights
  • Only way to eliminate CORS: Have both the frontend and the backend on the same origin.
  • If a.bank.com and b.bank.com need access to api.bank.com
    • CORS based solution could be api.bank.com allowing origins a.bank.com and b.bank.com
    • A better solution could be using an API gateway+reverse proxy. This would avoid CORS altogether.

Resources