What is CORS and how to configure it properly

· Category: Cybersecurity

What is CORS and how to configure it properly

What Is CORS?

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that controls how web pages request resources from a different domain. Without CORS, browsers block such requests by default under the Same-Origin Policy.

How CORS Works

The browser sends a preflight OPTIONS request for non-simple methods. The server responds with Access-Control-Allow-Origin and other headers. If the origin is permitted, the actual request proceeds.

Safe Configuration

Allow specific origins rather than wildcards when credentials are involved:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, origins=["https://app.example.com"], supports_credentials=True)

Common Misconfigurations

  • Access-Control-Allow-Origin: * with credentials enabled is invalid and dangerous.
  • Reflecting the request origin without validation opens the door to attacks.
  • Overly broad methods or headers increase exposure.

CORS is only a browser mechanism; always validate requests server-side. For header security beyond CORS, see how to implement Content Security Policy headers. For API design context, what is REST API clarifies endpoint boundaries.