Skip to content
Hossein Pira edited this page Aug 5, 2023 · 5 revisions

CORS (Cross-Origin Resource Sharing)

This document serves as a comprehensive guide to Cross-Origin Resource Sharing (CORS). It covers the fundamental concepts, methods, and important notes related to CORS. By the end, you will have a solid understanding of how CORS works and how to handle it in your applications.

Table of Contents

  1. Introduction to CORS
  2. Same-Origin Policy
  3. Cross-Origin Resource Sharing
  4. Simple Requests
  5. Preflight Requests
  6. Handling CORS on the Server
  7. Common CORS Issues and Troubleshooting
  8. Security Considerations
  9. Conclusion
  10. Additional Resources
  11. CORS Model

Introduction to CORS

Cross-Origin Resource Sharing (CORS) is a mechanism that allows a web page to make XMLHttpRequests to a different domain than the one it was served from. This is an important security feature implemented by web browsers to protect users from potential malicious behavior.

Same-Origin Policy

The Same-Origin Policy is a fundamental security concept in web browsers that restricts how a document or script loaded from one origin can interact with resources from another origin. The policy ensures that a web page's JavaScript can only access resources (e.g., data, cookies, and DOM) from the same origin.

Cross-Origin Resource Sharing

Cross-Origin Resource Sharing (CORS) is a W3C standard that relaxes the Same-Origin Policy and allows controlled access to resources from different origins. With CORS, a web application running in a browser can make cross-origin requests to access resources on a different domain.

Simple Requests

Simple requests are those that meet specific criteria defined by the CORS specification. These requests are automatically handled by the browser without the need for preflight requests. Simple requests must satisfy the following conditions:

  • Use methods like GET, POST, or HEAD
  • Have no custom headers other than Accept, Accept-Language, Content-Language, Content-Type (with some restrictions), and Last-Event-ID
  • Content-Type of the request must be one of the following: application/x-www-form-urlencoded, multipart/form-data, or text/plain

Preflight Requests

Preflight requests are used for non-simple requests. These requests are automatically issued by the browser before the actual request to check whether the server allows the actual request. Preflight requests include an HTTP OPTIONS method with specific headers to determine if the actual request is safe to send.

Handling CORS on the Server

To handle CORS on the server, you need to configure the server to respond with the appropriate CORS headers. These headers include:

  • Access-Control-Allow-Origin: Specifies the origins allowed to access the resource.
  • Access-Control-Allow-Methods: Specifies the HTTP methods allowed for the resource.
  • Access-Control-Allow-Headers: Specifies the custom headers allowed for the resource.
  • Access-Control-Allow-Credentials: Indicates whether the resource supports user credentials in requests.
  • Access-Control-Max-Age: Specifies how long the preflight request results can be cached.

The specific server-side configuration depends on the technology stack you're using. Refer to the documentation of your server framework or web server to learn how to configure CORS.

Common CORS Issues and Troubleshooting

CORS-related issues can arise due to misconfiguration or incorrect handling on the server or client side. Some common issues include:

  • Missing or incorrect CORS headers in the server response.
  • Sending credentials (cookies, HTTP authentication) without proper configuration.
  • Non-matching origins between the client and server.
  • Caching of preflight requests causing outdated responses.

When troubleshooting CORS issues, check the server's CORS configuration, ensure the client-side code is correctly set up, and examine the browser's developer console for error messages.

Security Considerations

While CORS allows controlled cross-origin access, it's crucial to implement appropriate security measures. Some important security considerations include:

  • Restricting the allowed origins to only those necessary for your application.
  • Avoiding the use of the wildcard (*) for the Access-Control-Allow-Origin header when credentials are involved.
  • Implementing proper authentication and authorization mechanisms.
  • Using secure communication protocols (HTTPS) to protect sensitive data.

Conclusion

Cross-Origin Resource Sharing (CORS) is a vital mechanism that enables controlled access to resources from different origins. Understanding how CORS works and how to handle it correctly is essential for building modern web applications that interact with multiple domains.

Additional Resources

CORS Model

This PHP Class provides a simple way to handle Cross-Origin Resource Sharing (CORS) headers in your PHP application. It allows you to define the allowed origins, methods, headers, exposed headers, max age, and whether to allow credentials.

Usage

  1. Create an instance of the CORS class, passing the desired CORS settings as parameters to the constructor.
use Monster\App\Models\CORS;

// Create a new instance of the CORS class
$cors = new CORS();

// Define CORS settings
$cors->origin(array('http://example.com', 'https://example.com'));
$cors->methods(array('GET', 'POST', 'PUT', 'DELETE'));
$cors->headers(array('Content-Type', 'Authorization'));
$cors->expose(array('X-Custom-Header'));
$cors->maxAge(3600)
$cors->credentials(true)
  1. Call the setHeaders method to set the CORS headers based on the configured settings.
// Set CORS headers
$cors->setHeaders();

Methods

The constructor method initializes the CORS settings.

  • $cors->origin (array): An array of allowed origins. Defaults to an empty array.
  • $cors->methods (array): An array of allowed HTTP methods. Defaults to an empty array.
  • $cors->headers (array): An array of allowed headers. Defaults to an empty array.
  • $cors->expose (array): An array of exposed headers. Defaults to an empty array.
  • $cors->maxAge (int): The maximum age of the preflight request result cache, in seconds. Defaults to 0.
  • $cors->credentials (bool): Whether to allow credentials (e.g., cookies, authorization headers). Defaults to false.

setHeaders()

This method sets the CORS headers based on the configured settings.

Example

Here's an example of how to use the CORS Model:

<?php

namespace Monster\App\Controllers;

use Monster\App\Models\CORS;

class AppController
{
    public function index()
    {
        $cors = new CORS();
        $cors->origin(['https://example.com', 'http://localhost:7000'])
            ->methods(['GET', 'POST'])
            ->headers(['Content-Type', 'Authorization'])
            ->expose(['Content-Length'])
            ->maxAge(0)
            ->credentials(false)
            ->setHeaders();

        echo "Hello";
    }
}

This will set the appropriate CORS headers in the HTTP response based on the specified settings.

Notes

  • The setHeaders method should be called before any output is sent to the browser.
  • Make sure to configure the allowed origins, methods, headers, and exposed headers according to your specific requirements.
  • It's recommended to adjust the CORS settings based on the security needs of your application.