Course contentsShow
← Security
Lesson 1041 of 3,05221. Web Security - API SecurityFree lesson

API Security Headers and CORS

Configure security headers, CORS policies, and content security for APIs to protect against common attacks.

API Security Headers and CORS

What you'll learn: How to configure HTTP security headers and Cross-Origin Resource Sharing (CORS) policies to protect your API from client-side attacks and unauthorized access.

Why Security Headers Matter for APIs

When your API sends responses back to browsers, HTTP headers act like safety instructions. They tell the browser how to handle the response securely. Without proper headers, attackers can exploit browsers to steal data, execute malicious scripts, or hijack sessions.

Think of security headers as warnings on prescription medication—they guide safe usage and prevent dangerous misuse.

Essential API Security Headers

X-Content-Type-Options: Set to nosniff to prevent browsers from MIME-sniffing responses and treating JSON as HTML.

X-Frame-Options: Use DENY to prevent your API responses from being embedded in iframes (clickjacking protection).

Strict-Transport-Security (HSTS): Forces browsers to always use HTTPS when communicating with your API: Strict-Transport-Security: max-age=31536000; includeSubDomains.

Content-Security-Policy (CSP): Restricts what resources the browser can load, preventing XSS attacks if your API accidentally returns HTML.

Understanding CORS

Cross-Origin Resource Sharing (CORS) controls which websites can call your API from JavaScript. Without CORS, browsers block requests from example.com to api.yoursite.com for security.

Configure CORS carefully:

  • Access-Control-Allow-Origin: Specify allowed origins (https://trusted-site.com), never use * for authenticated APIs
  • Access-Control-Allow-Methods: List permitted HTTP methods (GET, POST, etc.)
  • Access-Control-Allow-Headers: Define acceptable request headers
  • Access-Control-Allow-Credentials: Set to true only when needed for cookies/auth

Overly permissive CORS (* wildcards) lets any website call your API, enabling data theft and CSRF attacks.

Key Takeaway: Security headers and strict CORS policies create essential browser-side defenses that prevent attackers from exploiting your API through malicious websites or script injection, complementing your server-side security controls.