CORS request with Credentials

Credentials with CORS

Credentials can be cookies, Authorization headers or TLS Client Certificates. CORS requests do not send the Credentials by default.

How do I get CORS requests to send Credentials?

For the CORS request with Credentials to succeed, both the front and back ends need to be configured. Otherwise, even if the server agrees to send cookies, the browser won’t. Or, if the server asks for a Cookie, the browser won’t handle it.

Cookies still follow the same origin policy. Only cookies set by the server domain name will be uploaded, and cookies of other domain names will not be uploaded

configuration

Backend configuration: Access-Control-Allow-Credentials Header; Front end configuration: XHR withCredentials or Fetch Request withCredentials

Access-Control-Allow-Credentials

Its value is a Boolean value indicating whether cookies are allowed. By default, cookies are not included in CORS requests. Set to true to indicate explicit permission from the server that cookies can be included in the request and sent to the server. If the server does not want the browser to send cookies, delete this field.

Request.credentials

The Credentials are a read-only property of the Request interface that indicates whether the user agent should send cookies from other domains in the case of cross-domain requests. There are three optional values:

  • omit: Never send cookies.
  • same-originCookies, HTTP Basic Authentication and other authentication information are sent only if the URL is the same as the response script.
  • include: Whether it is a cross-domain request or not, always send cookies, HTTP Basic Authentication and other authentication information in the local domain of the requested resource.

XMLHttpRequest.withCredentials

WithCredentials are a Boolean type, and if true, the Credentials will be taken when making cross-domain requests, but otherwise they will not. The default value is false.

  • If not set before sending an XMLHttpRequest request from another domainwithCredentialsIf true, the cookie value cannot be set for its own field.
  • By setting thewithCredentialsThird-party cookies obtained for true will still be subject to the same origin policy and cannot be accessed through document.cookie or corresponding scripts requested from the header.
  • Used under the same sitewithCredentialsProperty is invalid. It will never affect same-origin requests.

example

Backend allows Credentials:

Access-Control-Allow-Credentials: true

The front end uses XHR requests with Credentials:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);

The front end uses the FETCH request with the Credentials:

fetch(url, {
  credentials: 'include'
})

When the credentials are included, access-control-allow-credentials must be set to true; When the credentials are other values, you can leave access-control-allow-credentials unset.