CORS (Cross-Origin Resource Sharing) is a security feature implemented in web browsers to prevent malicious scripts from making requests on behalf of the user, thereby reducing the risk of cross-site scripting (XSS) attacks.
What is CORS?
When a web application makes an HTTP request to a different origin (domain, protocol, or port), the browser will block the request by default. This is known as the "same-origin policy". CORS allows the server hosting the API to relax this policy and allow requests from specific origins.
Preflight Requests
Before sending a request, the client sends an HTTP OPTIONS request to the server, known as a preflight request. The server must respond with the allowed methods, headers, and any other relevant information.
OPTIONS /api/endpoint HTTP/1.1
Origin: https://example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
Origin Matching
The server must check if the origin of the request matches the allowed origins in the Access-Control-Allow-Origin header.
HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: https://example.com
In this example, only requests from https://example.com are allowed to access the API.
Credential Handling
When a request includes credentials (e.g., cookies or authorization headers), the server must respond with the correct Access-Control-Allow-Credentials header.
HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Credentials: true
Common Misconfigurations
- Missing CORS headers: Failing to include the necessary CORS headers in the response can result in blocked requests.
- Incorrect origin matching: Allowing access from an incorrect or wildcard origin can expose sensitive data.
- Credential handling issues: Incorrectly configuring credential handling can lead to security vulnerabilities.
Example Code (Node.js)
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: ['https://example.com'],
credentials: true,
}));
app.get('/api/endpoint', (req, res) => {
// API logic here
});
Example Code (Python with Flask)
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origins=['https://example.com'], allow_credentials=True)
@app.route('/api/endpoint', methods=['GET'])
def get_endpoint():
# API logic here
return jsonify({'message': 'Hello, World!'})