Sobes.tech
Middle

What is CORS, why is it needed, and how does it work?

sobes.tech AI

Answer from AI

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from accessing resources located on a different domain (origin). It is used to prevent unauthorized access and protect users from CSRF attacks.

How CORS works:

  • When a browser makes a request from one domain to another (e.g., from example.com to api.example.org), it automatically adds an Origin header indicating the source.
  • The server, upon receiving the request, checks this header and decides whether to allow the request, adding an Access-Control-Allow-Origin header with the permitted domain in the response.
  • If the header is absent or the domain does not match, the browser blocks access to the response.

For complex requests (e.g., with POST method and custom headers), the browser first sends a preflight OPTIONS request to check permissions.

Example of CORS configuration in Python with Flask and flask-cors extension:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "https://example.com"}})

@app.route('/api/data')
def data():
    return {'key': 'value'}

Here, the server will only allow requests from https://example.com to routes starting with /api/.

What is CORS, why is it needed, and how does it work… - sobes.tech