Understanding Web Security: The Complementary Roles of CSRF Protection and CORS

· 1 min read

article picture

The modern web relies on two seemingly contradictory security mechanisms - CSRF protection blocks cross-site requests, while CORS enables them. Here's why we need both.

CSRF (Cross-Site Request Forgery) protection emerged in the early days of the internet to prevent malicious websites from tricking users into submitting unauthorized requests. When you click a deceptive link or button, it could trigger a form submission to another website using your existing login session.

Meanwhile, CORS (Cross-Origin Resource Sharing) provides a framework for websites to selectively allow cross-origin requests. Through special HTTP headers, servers can specify which external domains can access their resources.

The key lies in understanding the browser's default behavior. By design, browsers allow cross-origin form submissions but block reading the responses. This maintains backwards compatibility with traditional HTML forms while preventing unauthorized data access.

CORS builds on this foundation by giving servers fine-grained control over which cross-origin requests are permitted. Before allowing certain requests like PATCH or DELETE, browsers send "preflight" OPTIONS requests to check the server's cross-origin policies.

However, basic form submissions bypass CORS restrictions due to historical reasons. When HTML forms were introduced in HTML 4.0, cross-origin submissions were already possible. Rather than break existing websites, browsers continue allowing these "simple" POST requests.

This creates a security gap that CSRF protection fills. By requiring a special token in requests, CSRF protection ensures that form submissions genuinely originated from your website rather than a malicious third-party.

Recent browser updates aim to improve security through the SameSite cookie attribute. When set to "Lax" (the new default in most browsers), cookies are no longer automatically included in cross-site POST requests. However, adoption remains incomplete.

The browser plays the central role in enforcing these security boundaries. It manages site data, implements same-origin restrictions, blocks unauthorized response access, and handles CORS preflight requests. The entire system depends on browsers correctly implementing these protections.

Until all browsers adopt stricter defaults, websites need both CSRF protection and CORS to handle different types of cross-origin requests securely. CSRF tokens verify legitimate form submissions, while CORS provides granular control over modern cross-origin API access.