Book Image

CORS Essentials

By : Rajesh Gunasundaram
Book Image

CORS Essentials

By: Rajesh Gunasundaram

Overview of this book

This book explains how to use CORS, including specific implementations for platforms such as Drupal, WordPress, IIS Server, ASP.NET, JBoss, Windows Azure, and Salesforce, as well as how to use CORS in the Cloud on Amazon AWS, YouTube, Mulesoft, and others. It examines limitations, security risks, and alternatives to CORS. It explores the W3C Specification and major developer documentation sources about CORS. It attempts to predict what kinds of extension to the CORS specification, or completely new techniques, will come in the future to address the limitations of CORS Web developers will learn how to share code and assets across domains with CORS. They will learn a variety of techniques that are rather similar in their method and syntax. The book is organized by similar types of framework and application, so it can be used as a reference. Developers will learn about special cases, such as when a proxy is necessary. And they will learn about some alternative techniques that achieve similar goals, and when they may be preferable to using CORS
Table of Contents (15 chapters)
CORS Essentials
Credits
About the Authors
www.PacktPub.com
Customer Feedback
Preface
Index

CORS with Preflight


Preflight is a request the XHR object makes to ensure it's allowed to make another request.

Note

The CORS specification requires browsers to preflight requests that do the following:

  • Use any methods in the request other than GET, POST, or HEAD.

  • Include custom headers

  • Include content-type other than text/plain, application/x-www-form-urlencoded, or multipart/form-data

There's no preflight by default in CORS. Adding preflight makes your application more robust and handles errors better. However, it can also introduce complexities, which may be unnecessary when you are confident that the XHR request you need to make will be answered, and you only need to use GET, POST, or HEAD.

Triggering a preflight by setting a custom header

To trigger a preflight, set custom headers on the XHR request; the Access-Control-Allow-Methods header determines which HTTP methods can be used.

The preflight request

The following PHP code verifies for the OPTIONS request method during preflight. The server responds with the X-Requested-With header permitted:

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  // return only headers
  // The Preflight checks that the GET request method is supported
  if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'GET') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: X-Requested-With');
  }
  exit;
}else{
  // error-handling code if the OPTIONS request method is unavailable
}

The preflight response

A successful server response returns the X-Requested-With method:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With

CORS via jQuery

CORS via jQuery does not use preflight.

jQuery specifically avoids setting the custom header when making a CORS request. Therefore, it is better to use a separate preflight method when using jQuery for CORS.

Note

Here is the comment in the jQuery xhr.js library explaining why preflight is not used:

// X-Requested-With header

// For cross-domain requests, seeing as conditions for a preflight are

// akin to a jigsaw puzzle, we simply never set it to be sure.

// (it can always be set on a per-request basis or even using AJAXSetup)

// For same-domain requests, won't change header if already provided.

Known issues with CORS preflight

There are some common issues that developers face while implementing CORS preflight.

Preflight in Firefox

The CORS preflight request fails in Firefox when the OPTIONS request needs to be authenticated, causing the cross-origin request to fail. The request fails because authentication tokens are not sent with the preflight request. If the OPTIONS request fails, the preflight will result in 405 (method not allowed). Firefox ignores the request when the preflight fails.

Preflight in Chrome

Unlike Firefox, Chrome allows the request even if the option fails in preflight if the request and response headers are correct.

Preflight in Internet Explorer

Even when using withCredentials, IE doesn't send the auth tokens to preflight.

Tip

Should we avoid preflight entirely?

The best advice is to avoid using preflight entirely, unless you need to check whether requests are allowed.

Non-simple CORS request methods and headers require preflight

Any CORS request that uses a non-simple method or header requires preflight.

GET, POST, and HEAD are considered simple requests (and are case-sensitive). They do not require preflight.

The simple headers that do not require preflight are as follows:

  • Cache-control

  • Content-language

  • Content-type

  • Expires

  • Last-modified

  • Pragma

Any other method or header requires preflight.

Using the XMLHttpRequest level 2 event HandlersOriginally, XMLHttpRequest had only one event handler: onreadystatechange. XMLHttpRequest2 introduces new event handlers.

You may have noticed that when defining the XHR objects, we have used request.onload, which corresponds to the onload event when the request has successfully completed since we are interested in knowing whether the request has been successful.

Event handler

Description

Onreadystatechange

readyState property changes

onloadstart*

request starts

Onprogress

during loading and sending data.

onabort*

request has been aborted

Onerror

request has failed

Onload

request has successfully completed

ontimeout

specified timeout has expired before the request could complete

onloadend*

request has completed (success or failure)

* IE's XdomainRequest does not support handlers marked with asterisks

Checking for the withCredentials property

Check whether withCredentials property is available to determine whether the browser supports XMLHttpRequest level 2 event handlers. This could be handled as a preflight.