Back to learning

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that controls how web pages in one origin can request and interact with resources hosted on another origin.

Why is CORS needed?

By default, a web page's scripts cannot make requests to a different domain than the one the web page came from. This restriction is known as the "same-origin policy" and is in place to prevent potentially malicious actions, such as cross-site request forgery attacks. However, in today's interconnected web landscape, there are legitimate scenarios where a web page might need to access resources (like APIs) from another domain. CORS provides a secure way to allow exceptions to the same-origin policy.

How does CORS work?

When a web page makes a cross-origin request, the browser sends the request with an Origin header indicating where the request comes from. The server can then decide whether to permit the request based on its CORS configuration. If allowed, the server sends back an Access-Control-Allow-Origin header in its response, matching the origin of the requester or a wildcard (*), indicating that the requester is permitted to access the resource.

Key Components of CORS:

  1. Headers: CORS works with specific HTTP headers, which signal both the requests' permissions and the servers' allowances. Common headers include: Origin: Sent by the browser to indicate the domain of the calling web page. Access-Control-Allow-Origin: Sent by the server to specify which origins are permitted. Access-Control-Allow-Methods: Specifies which HTTP methods (like GET, POST, etc.) are allowed. Access-Control-Allow-Headers: Indicates which HTTP headers can be used in the actual request.
  2. Pre-flight Request: Before making certain types of cross-origin requests, browsers will automatically send a pre-flight request (using the OPTIONS HTTP method) to check if the actual request is permitted.
  3. Credentials: By default, cross-origin requests do not include cookies or other credentials. If credentials are required, both the frontend request and the server's response need specific configurations: the frontend would use withCredentials, and the server should include the header Access-Control-Allow-Credentials: true.

Potential Issues:

A common challenge developers face is the "CORS error." This error occurs when either:

  • The server hasn't been configured to handle CORS requests.
  • The server's CORS configuration doesn't match what the requesting page is allowed to do.
  • In such cases, the browser will block the request for security reasons, and an error will typically appear in the browser's developer console.

Adjusting CORS policies should be done with care, as overly permissive settings can expose web resources to security risks.

© PEAKHOUR.IO PTY LTD 2024   ABN 76 619 930 826    All rights reserved.