This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.
CORS Security
CORS Security
CORS Security
CORS Security
CORS Security
CORS Security
CORS Security
CORS Security
CORS Security
CORS Security
CORS Security
Introduction
Cross-Origin Resource Sharing (CORS) is a browser mechanism that controls which origins can access resources on a different origin. While CORS enables legitimate cross-origin requests, misconfigurations are among the most common security vulnerabilities discovered in modern web applications.
How CORS Works
CORS works through HTTP headers that the server sends to tell the browser which origins are permitted. The browser enforces these restrictions on the client side.
Simple Requests
A simple request uses standard methods (GET, HEAD, POST) and headers. The browser adds an Origin header, and the server responds with Access-Control-Allow-Origin.
Request:
GET /api/data HTTP/1.1
Origin: https://trusted-app.com
Response:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://trusted-app.com
Preflight Requests
For non-simple requests (custom headers, PUT, DELETE, content types other than form data), the browser sends an OPTIONS preflight request first.
Preflight:
OPTIONS /api/data HTTP/1.1
Origin: https://trusted-app.com
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: X-Custom-Header
Response:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://trusted-app.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Max-Age: 3600
Proper Origin Validation
Never reflect the Origin header back unconditionally. This is the most common dangerous CORS misconfiguration.
UNSAFE: Reflective origin (vulnerable to attack)
def cors_unsafe(request):
origin = request.headers.get('Origin')
response.headers['Access-Control-Allow-Origin'] = origin # NEVER do this
response.headers['Access-Control-Allow-Credentials'] = 'true'
SAFE: Whitelist-based origin validation
ALLOWED
Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.
Found this useful? Check out more developer guides and tool comparisons on AI Study Room.
Top comments (0)