tl;dr — When you want to read data, (mostly) using client-side JS, from a different server you need the server with the data to grant explicit permission to the code that wants the data.
There’s a summary at the end and headings in the answer to make it easier to find the relevant parts. Reading everything is recommended though as it provides useful background for understanding the why that makes seeing how the how applies in different circumstances easier.
About the Same Origin Policy
This is the Same Origin Policy. It is a security feature implemented by browsers.
Your particular case is showing how it is implemented for XMLHttpRequest (and you’ll get identical results if you were to use fetch), but it also applies to other things (such as images loaded onto a <canvas> or documents loaded into an <iframe>), just with slightly different implementations.
The standard scenario that demonstrates the need for the SOP can be demonstrated with three characters:
- Alice is a person with a web browser
- Bob runs a website (
https://www.example.com/in your example) - Mallory runs a website (
http://localhost:4300in your example)
Alice is logged into Bob’s site and has some confidential data there. Perhaps it is a company intranet (accessible only to browsers on the LAN), or her online banking (accessible only with a cookie you get after entering a username and password).
Alice visits Mallory’s website which has some JavaScript that causes Alice’s browser to make an HTTP request to Bob’s website (from her IP address with her cookies, etc). This could be as simple as using XMLHttpRequest and reading the responseText.
The browser’s Same Origin Policy prevents that JavaScript from reading the data returned by Bob’s website (which Bob and Alice don’t want Mallory to access). (Note that you can, for example, display an image using an <img> element across origins because the content of the image is not exposed to JavaScript (or Mallory) … unless you throw canvas into the mix in which case you will generate a same-origin violation error).
Why the Same Origin Policy applies when you don’t think it should
For any given URL it is possible that the SOP is not needed. A couple of common scenarios where this is the case are:
- Alice, Bob, and Mallory are the same person.
- Bob is providing entirely public information
… but the browser has no way of knowing if either of the above is true, so trust is not automatic and the SOP is applied. Permission has to be granted explicitly before the browser will give the data it has received from Bob to some other website.
Why the Same Origin Policy applies to JavaScript in a web page but little else
Outside the web page
Browser extensions*, the Network tab in browser developer tools, and applications like Postman are installed software. They aren’t passing data from one website to the JavaScript belonging to a different website just because you visited that different website. Installing software usually takes a more conscious choice.
There isn’t a third party (Mallory) who is considered a risk.
* Browser extensions do need to be written carefully to avoid cross-origin issues. See the Chrome documentation for example.
Inside the webpage
Most of the time, there isn’t a great deal of information leakage when just showing something on a webpage.
If you use an <img> element to load an image, then it gets shown on the page, but very little information is exposed to Mallory. JavaScript can’t read the image (unless you use a crossOrigin attribute to explicitly enable request permission with CORS) and then copy it to her server.
That said, some information does leak so, to quote Domenic Denicola (of Google):
The web’s fundamental security model is the same origin policy. We
have several legacy exceptions to that rule from before that security
model was in place, with script tags being one of the most egregious
and most dangerous. (See the various «JSONP» attacks.)Many years ago, perhaps with the introduction of XHR or web fonts (I
can’t recall precisely), we drew a line in the sand, and said no new
web platform features would break the same origin policy. The existing
features need to be grandfathered in and subject to carefully-honed
and oft-exploited exceptions, for the sake of not breaking the web,
but we certainly can’t add any more holes to our security policy.
This is why you need CORS permission to load fonts across origins.
Why you can display data on the page without reading it with JS
There are a number of circumstances where Mallory’s site can cause a browser to fetch data from a third party and display it (e.g. by adding an <img> element to display an image). It isn’t possible for Mallory’s JavaScript to read the data in that resource though, only Alice’s browser and Bob’s server can do that, so it is still secure.
CORS
The Access-Control-Allow-Origin HTTP response header referred to in the error message is part of the CORS standard which allows Bob to explicitly grant permission to Mallory’s site to access the data via Alice’s browser.
A basic implementation would just include:
Access-Control-Allow-Origin: *
… in the response headers to permit any website to read the data.
Access-Control-Allow-Origin: http://example.com
… would allow only a specific site to access it, and Bob can dynamically generate that based on the Origin request header to permit multiple, but not all, sites to access it.
The specifics of how Bob sets that response header depend on Bob’s HTTP server and/or server-side programming language. Users of Node.js/Express.js should use the well-documented CORS middleware. Users of other platforms should take a look at this collection of guides for various common configurations that might help.
NB: Some requests are complex and send a preflight OPTIONS request that the server will have to respond to before the browser will send the GET/POST/PUT/Whatever request that the JS wants to make. Implementations of CORS that only add Access-Control-Allow-Origin to specific URLs often get tripped up by this.
Obviously granting permission via CORS is something Bob would only do only if either:
- The data was not private or
- Mallory was trusted
How do I add these headers?
It depends on your server-side environment.
If you can, use a library designed to handle CORS as they will present you with simple options instead of having to deal with everything manually.
Enable-Cors.org has a list of documentation for specific platforms and frameworks that you might find useful.
But I’m not Bob!
There is no standard mechanism for Mallory to add this header because it has to come from Bob’s website, which she does not control.
If Bob is running a public API then there might be a mechanism to turn on CORS (perhaps by formatting the request in a certain way, or a config option after logging into a Developer Portal site for Bob’s site). This will have to be a mechanism implemented by Bob though. Mallory could read the documentation on Bob’s site to see if something is available, or she could talk to Bob and ask him to implement CORS.
Error messages which mention «Response for preflight»
Some cross-origin requests are preflighted.
This happens when (roughly speaking) you try to make a cross-origin request that:
- Includes credentials like cookies
- Couldn’t be generated with a regular HTML form (e.g. has custom headers or a Content-Type that you couldn’t use in a form’s
enctype).
If you are correctly doing something that needs a preflight
In these cases then the rest of this answer still applies but you also need to make sure that the server can listen for the preflight request (which will be OPTIONS (and not GET, POST, or whatever you were trying to send) and respond to it with the right Access-Control-Allow-Origin header but also Access-Control-Allow-Methods and Access-Control-Allow-Headers to allow your specific HTTP methods or headers.
If you are triggering a preflight by mistake
Sometimes people make mistakes when trying to construct Ajax requests, and sometimes these trigger the need for a preflight. If the API is designed to allow cross-origin requests but doesn’t require anything that would need a preflight, then this can break access.
Common mistakes that trigger this include:
- trying to put
Access-Control-Allow-Originand other CORS response headers on the request. These don’t belong on the request, don’t do anything helpful (what would be the point of a permissions system where you could grant yourself permission?), and must appear only on the response. - trying to put a
Content-Type: application/jsonheader on a GET request that has no request body the content of which to describe (typically when the author confusesContent-TypeandAccept).
In either of these cases, removing the extra request header will often be enough to avoid the need for a preflight (which will solve the problem when communicating with APIs that support simple requests but not preflighted requests).
Opaque responses (no-cors mode)
Sometimes you need to make an HTTP request, but you don’t need to read the response. e.g. if you are posting a log message to the server for recording.
If you are using the fetch API (rather than XMLHttpRequest), then you can configure it to not try to use CORS.
Note that this won’t let you do anything that you require CORS to do. You will not be able to read the response. You will not be able to make a request that requires a preflight.
It will let you make a simple request, not see the response, and not fill the Developer Console with error messages.
How to do it is explained by the Chrome error message given when you make a request using fetch and don’t get permission to view the response with CORS:
Access to fetch at ‘
https://example.com/‘ from origin ‘https://example.net‘ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
Thus:
fetch("http://example.com", { mode: "no-cors" });
Alternatives to CORS
JSONP
Bob could also provide the data using a hack like JSONP which is how people did cross-origin Ajax before CORS came along.
It works by presenting the data in the form of a JavaScript program that injects the data into Mallory’s page.
It requires that Mallory trust Bob not to provide malicious code.
Note the common theme: The site providing the data has to tell the browser that it is OK for a third-party site to access the data it is sending to the browser.
Since JSONP works by appending a <script> element to load the data in the form of a JavaScript program that calls a function already in the page, attempting to use the JSONP technique on a URL that returns JSON will fail — typically with a CORB error — because JSON is not JavaScript.
Move the two resources to a single Origin
If the HTML document the JS runs in and the URL being requested are on the same origin (sharing the same scheme, hostname, and port) then the Same Origin Policy grants permission by default. CORS is not needed.
A Proxy
Mallory could use server-side code to fetch the data (which she could then pass from her server to Alice’s browser through HTTP as usual).
It will either:
- add CORS headers
- convert the response to JSONP
- exist on the same origin as the HTML document
That server-side code could be written & hosted by a third party (such as CORS Anywhere). Note the privacy implications of this: The third party can monitor who proxies what across their servers.
Bob wouldn’t need to grant any permissions for that to happen.
There are no security implications here since that is just between Mallory and Bob. There is no way for Bob to think that Mallory is Alice and to provide Mallory with data that should be kept confidential between Alice and Bob.
Consequently, Mallory can only use this technique to read public data.
Do note, however, that taking content from someone else’s website and displaying it on your own might be a violation of copyright and open you up to legal action.
Writing something other than a web app
As noted in the section «Why the Same Origin Policy only applies to JavaScript in a web page», you can avoid the SOP by not writing JavaScript in a webpage.
That doesn’t mean you can’t continue to use JavaScript and HTML, but you could distribute it using some other mechanism, such as Node-WebKit or PhoneGap.
Browser extensions
It is possible for a browser extension to inject the CORS headers in the response before the Same Origin Policy is applied.
These can be useful for development but are not practical for a production site (asking every user of your site to install a browser extension that disables a security feature of their browser is unreasonable).
They also tend to work only with simple requests (failing when handling preflight OPTIONS requests).
Having a proper development environment with a local development server
is usually a better approach.
Other security risks
Note that SOP / CORS do not mitigate XSS, CSRF, or SQL Injection attacks which need to be handled independently.
Summary
- There is nothing you can do in your client-side code that will enable CORS access to someone else’s server.
- If you control the server the request is being made to: Add CORS permissions to it.
- If you are friendly with the person who controls it: Get them to add CORS permissions to it.
- If it is a public service:
- Read their API documentation to see what they say about accessing it with client-side JavaScript:
- They might tell you to use specific URLs
- They might support JSONP
- They might not support cross-origin access from client-side code at all (this might be a deliberate decision on security grounds, especially if you have to pass a personalized API Key in each request).
- Make sure you aren’t triggering a preflight request you don’t need. The API might grant permission for simple requests but not preflighted requests.
- Read their API documentation to see what they say about accessing it with client-side JavaScript:
- If none of the above apply: Get the browser to talk to your server instead, and then have your server fetch the data from the other server and pass it on. (There are also third-party hosted services that attach CORS headers to publically accessible resources that you could use).
![[logo] CORS - Cross-origin resource sharing](https://static.itmag.pro/images/logo/cors-logo_1.jpg)
Здесь мы условились о том, что:
- src.example.org — это домен, с которого отправляются XMLHttpRequest кросс-доменные запросы
- target.example.com/example.php — это домен и скрипт /example.php, на который XMLHttpRequest кросс-доменные запросы отправляются
Перечисленные ниже CORS ошибки приводятся в том виде, в котором они выдавались в консоль веб-браузера.
https://target.example.com/example.php в данном примере фактически был размещён на сервере страны отличной от Украины и посредством CURL предоставлял доступ к российскому сервису проверки правописания от Яндекса, — как извесно доступ к сервисам Яндекса из Украины был заблокирован большинством Интернет-провайдеров.
При попытке проверить правописание в редакторе выдавалась ошибка: «The spelling service was not found: (https://target.example.com/example.php)«
Причина: отсутствует заголовок CORS ‘Access-Control-Allow-Origin’
«NetworkError: 403 Forbidden — https://target.example.com/example.php»
example.php
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: отсутствует заголовок CORS ‘Access-Control-Allow-Origin’).
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: не удалось выполнить запрос CORS).
Решение: отсутствует заголовок CORS ‘Access-Control-Allow-Origin’
CORS для src.example.org должно быть разрешено на стороне сервера принимающего запросы — это можно сделать в .htaccess следующим образом:
<Files ~ "(example)+.php"> Header set Access-Control-Allow-Origin "https://src.example.org" </Files>
Причина: неудача канала CORS preflight
«NetworkError: 403 Forbidden — https://target.example.com/example.php» example.php
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: неудача канала CORS preflight).
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: не удалось выполнить запрос CORS).
Решение: неудача канала CORS preflight
Причины здесь могут быть разные, среди которых может быть запрет некоторых ИП на стороне брандмауэра, либо ограничения на методы запроса в том же .htaccess строкой: «RewriteCond %{REQUEST_METHOD} !^(post|get) [NC,OR]«.
Во-втором случае это может быть зафиксировано в лог-файле ошибок сервера:
xxx.xxx.xx.xxx [07/May/2018:09:55:15 +0300] «OPTIONS /example.php HTTP/1.1» 403 «Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:52.0) Gecko/20100101 Firefox/52.0» «Referer: -«
Примечание:
Нужно помнить, что ИП-адрес в лог-файле сервера принадлежит клиенту/браузеру, а не удалённому серверу src.example.org на страницах которого в браузере клиента был инициирован CORS (кросс-доменный) запрос!
В случае с .htaccess строку подправим до такого состояния: «RewriteCond %{REQUEST_METHOD} !^(post|get|options) [NC,OR]«.
Причина: отсутствует токен ‘x-requested-with’ в заголовке CORS ‘Access-Control-Allow-Headers’ из канала CORS preflight
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: отсутствует токен ‘x-requested-with’ в заголовке CORS ‘Access-Control-Allow-Headers‘ из канала CORS preflight).
Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на https://target.example.com/example.php. (Причина: не удалось выполнить запрос CORS).
Решение: отсутствует токен ‘x-requested-with’ в заголовке CORS ‘Access-Control-Allow-Headers’ из канала CORS preflight
Посредством .htaccess добавим заголовок Access-Control-Allow-Headers:
<Files ~ "(example)+.php"> Header set Access-Control-Allow-Origin "https://src.example.org" Header set Access-Control-Allow-Headers: "X-Requested-With" </Files>
Access-Control-Allow-Origin для множества доменов
Заголовок Access-Control-Allow-Origin допускает установку только одного источника, однако при необходимости разрешения CORS для множества источников в .htaccess можно извратится следующим образом:
##### ---+++ BEGIN MOD HEADERS CONFIG +++--- <IfModule mod_headers.c> <Files ~ "(example)+.php"> #Header set crossDomain: true # ## Allow CORS from one domain #Header set Access-Control-Allow-Origin "https://src.example.org" ## Allow CORS from multiple domain SetEnvIf Origin "http(s)?://(www.)?(example.org|src.example.org)$" AccessControlAllowOrigin=$0 Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin # ## Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token Header set Access-Control-Allow-Headers: "X-Requested-With" # ## "GET, POST" Header set Access-Control-Allow-Methods "POST" # #Header set Access-Control-Allow-Credentials true #Header set Access-Control-Max-Age 60 </Files> </IfModule> ##### ---+++// END MOD HEADERS CONFIG +++---
Время прочтения
8 мин
Просмотры 12K
В этой статье мы с вами разберемся, что такое CORS, CORS-ошибки и из-за чего мы можем с ними сталкиваться. Я также продемонстрирую возможные решения и объясню, что такое предварительные (preflight) запросы, CORS-заголовки и в чем заключается их важность при обмене данными между сторонами. Эта статья рассчитана на тех, у кого уже есть базовые познания в области веб-разработки и некоторый опыт с протоколом HTTP. Я старался писать статью так, чтобы она была понятна и новичкам, будучи наполненной знаниями, но при этом стараясь избегать слишком большого количества технических нюансов, не связанных с темой CORS. Если вы заметите какие-либо ошибки или у вас будут предложения, не стесняйтесь писать мне. В некоторых местах я нарочно делал упрощения, говоря “служба”, подразумевая “сервер”, и наоборот.
Что такое CORS?
Cross-Origin Resource Sharing (CORS или “совместное использование ресурсов различными источниками”) — это контролируемый и применяемый в принудительном порядке клиентом (браузером) механизм обеспечения безопасности на основе HTTP. Он позволяет службе (API) указывать любой источник (origin), помимо себя, из которого клиент может запрашивать ресурсы. Он был разработан в соответствии с same-origin policy (SOP или “политика одинакового источника”), которая ограничивает взаимодействие сайта (HTML-документа или JS-скрипта), загруженного из одного источника, с ресурсом из другого источника. CORS используется для явного разрешения определенных cross-origin запросов и отклонения всех остальных.
В основном CORS реализуют веб-браузеры, но как вариант его также можно использовать в API-клиентах. Он присутствует во всех популярных браузерах, таких как Google Chrome, Firefox, Opera и Safari. Этот стандарт был принят в качестве рекомендации W3C в январе 2014 года. Исходя из этого, можно смело предполагать, что он реализован во всех доступных в настоящее время браузерах, которые не были перечислены выше.
Как это работает?
Все начинается на стороне клиента, еще до отправки основного запроса. Клиент отправляет в службу с ресурсами предварительный (preflight) CORS-запрос с определенными параметрами в заголовках HTTP (CORS-заголовках, если быть точнее). Служба отвечает, используя те же заголовки с другими или такими же значениями. На основе ответа на предварительный CORS-запрос клиент решает, может ли он отправить основной запрос к службе. Браузер (клиент) выдаст ошибку, если ответ не соответствует требованиям предварительной проверки CORS.
Предварительные CORS-запросы отправляются независимо от используемых для отправки запросов из браузера библиотек или фреймворков. Поэтому вам не нужно соответствовать требованиям CORS, когда вы работе с API из вашего серверного приложения.
CORS не будет препятствовать пользователям запрашивать или загружать ресурсы. Вы прежнему можете успешно запросить ресурс с помощью таких приложений, как curl, Insomnia или Postman. CORS будет препятствовать доступу браузера к ресурсу только в том случае, если политика CORS не разрешает этого.
Что такое предварительная проверка CORS?
Когда браузер отправляет запрос на сервер, он сначала отправляет Options HTTP-запрос. Это и есть предварительным CORS-запрос. Затем сервер отвечает списком разрешенных методов и заголовков. Если браузеру разрешено сделать фактический запрос, то тогда он незамедлительно отправит его. Если нет, он покажет пользователю ошибку и не выполнит основной запрос.
CORS-заголовки
CORS-заголовки — это обычные заголовки HTTP, которые используются для контроля политики CORS. Они используются, когда браузер отправляет предварительный CORS-запрос на сервер, на который сервер отвечает следующими заголовками:
-
Access-Control-Allow-Originуказывает, какой источник может получать ресурсы. Вы можете указать один или несколько источников через запятую, например:https://foo.io,http://bar.io. -
Access-Control-Allow-Methodsуказывает, какие HTTP-методы разрешены. Вы можете указать один или несколько HTTP-методов через запятую, например:GET,PUT,POST. -
Access-Control-Allow-Headersуказывает, какие заголовки запросов разрешены. Вы можете указать один или несколько заголовков через запятую, например:Authorization,X-My-Token. -
Access-Control-Allow-Credentialsуказывает, разрешена ли отправка файлов cookie. По умолчанию:false. -
Access-Control-Max-Ageуказывает в секундах, как долго должен кэшироваться результат запроса. По умолчанию: 0.
Если вы решите использовать Access-Control-Allow-Credentials=true, то вам нужно знать, что вы не сможете использовать символы * в заголовках Access-Control-Allow-*. Необходимо будет явно перечислить все разрешенные источники, методы и заголовки.
Полный список CORS-заголовков вы можете найти здесь.
Почему запрос может быть заблокирован политикой CORS?
Если вы веб-разработчик, вы, вероятно, уже слышали или даже сталкивались с CORS-ошибками, имея за плечами часы, потраченные на поиски их причин и решений. Наиболее распространенная проблема заключается в том, что браузер блокирует запрос из-за политики CORS. Браузер выдаст ошибку и отобразит в консоли следующее сообщение:
Access to XMLHttpRequest at 'http://localhost:8080/' from origin
'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present
on the requested resource.
Приведенная выше CORS-ошибка уведомляет пользователя о том, что браузер не может получить доступ к ресурсу (https://localhost:8080) из источника (https://localhost:3000), поскольку сервер его не одобрил. Это произошло из-за того, что сервер не ответил заголовком Access-Control-Allow-Origin с этим источником или символом * в ответе на предварительный CORS-запрос.
Запрос может быть заблокирован политикой CORS не только из-за невалидного источника, но и из-за неразрешенных заголовка HTTP, HTTP-метода или заголовка Cookie.
Как исправить CORS-ошибку?
Фундаментальная идея “исправления CORS” заключается в том, чтобы отвечать на OPTIONS запросы, отправленные от клиента, корректными заголовками. Есть много способов начать отвечать корректными CORS. Вы можете использовать прокси-сервер или какое-нибудь middleware на своем сервере.
Помните, что заголовки Access-Control-* кэшируются в браузере в соответствии со значением, установленным в заголовке Access-Control-Max-Age. Поэтому перед тестированием изменений вам обязательно нужно чистить кэш. Вы также можете отключить кэширование в своем браузере.
1. Настройка вашего сервера
По умолчанию, если вы являетесь владельцем сервера, вам необходимо настроить на своем сервере CORS-ответы, и это единственный способ правильно решить проблему. Вы можете добиться этого несколькими способами из нескольких слоев вашего приложения. Самый распространенный способ — использовать обратный прокси-сервер (reverse-proxy), API-шлюз или любой другой сервис маршрутизации, который позволяет добавлять заголовки к ответам. Для этого можно использовать множество сервисов, и вот некоторые из них: HAProxy, Linkerd, Istio, Kong, nginx, Apache, Traefik. Если ваша инфраструктура содержит только приложение без каких-либо дополнительных слоев, то вы можете добавить поддержку CORS в код самого приложения.
Вот несколько популярных примеров активации CORS:
-
Apache: отредактируйте файл .htaccess
-
Nginx: отредактируйте файл конфигурации,
-
Traefik: используйте middleware,
-
Spring Boot: используйте аннотацию @EnableCORS,
-
ExpressJS: используйте app.use(cors()),
-
NextJS: используйте реквест-хелперы.
Здесь вы можете найти больше примеров активации CORS для разных фреймворков и языков: enable-cors.org.
Если вы не можете активировать CORS в службе, но все же хотите сделать возможными запросы к ней, то вам нужно использовать одно из следующих решений, описанных ниже.
2. Установка расширения для браузера
Использование расширения для браузера может быть быстрым и простым способом решения проблем с CORS в вашей среде разработки. Самым большим преимуществом использования расширения для браузера является то, что вам не нужно менять свой код или конфигурацию. С другой стороны, вам необходимо установить расширение в каждый браузер, который вы используете для тестирования своего веб-приложения.
Расширения для браузера изменяют входящий предварительный запрос, добавляя необходимые заголовки, чтобы обмануть браузер. Это очень удобное решение для локальной работы с производственным API, которое принимает запросы только из рабочего домена.
Вы можете найти расширения в Google Web Store или в библиотеке дополнений Mozilla. В некоторых случаях дефолтной конфигурации расширения может быть недостаточно; убедитесь, что установленное расширение корректно настроено. Вам также следует быть в курсе, что если держать подобное расширение включенным постоянно, то это может вызвать проблемы с некоторыми сайтами. Их рекомендуется использовать только в целях разработки.
3. Отключение CORS-проверок в браузере
Вы можете полностью отключить CORS-проверки в своем браузере. Чтобы отключить CORS-проверки в Google Chrome, нужно закрыть браузер и запустить его с флагами --disable-web-security и --user-data-dir. После запуска Google Chrome не будет отправлять предварительные CORS-запросы и не будет проверять CORS-заголовки.
# Windows
chrome.exe --user-data-dir="C://chrome-dev-disabled-security" --disable-web-security --disable-site-isolation-trials
# macOS
open /Applications/Google Chrome.app --args --user-data-dir="/var/tmp/chrome-dev-disabled-security" --disable-web-security --disable-site-isolation-trials
# Linux
google-chrome --user-data-dir="~/chrome-dev-disabled-security" --disable-web-security --disable-site-isolation-trials
Все команды, приведенные выше, запускают Google Chrome в изолированной безопасной среде. Они не затронут ваш основной профиль Chrome.
Список всех доступных флагов для Google Chrome можно найти здесь.
4. Настройка прокси-сервера
Если вы ищете решение, которое не требует от вас изменения настроек браузера, вам следует обратить внимание на прокси-сервера. Эта опция поможет вам избавиться от CORS-ошибок, ничего не меняя в самом браузере. Идея подхода заключается в том, чтобы отправлять все запросы на ваш сервер, который затем перенаправит запрос реальной службе, которую вы хотите использовать. Вы можете создать прокси-сервер самостоятельно с помощью языка и платформы по вашему предпочтению. Вам потребуется настроить CORS и реализовать функционал передачи полученных запросов в другую службу.
Прокси-сервер — хорошее решение, если у вас нет доступа к службе, которую вы собираетесь использовать. Существует множество готовых к использованию решений с открытым исходным кодом для создания прокси-серверов, но вам обязательно нужно следить за тем, чтобы они не пытались перехватить ваши запросы с заголовками авторизации и передать их какой-либо сторонней службе. Такие нарушения безопасности могут привести к катастрофическим последствиям как для вас, так и для потенциальных пользователей службы.
Ниже приведен список CORS сервисов с открытым исходным кодом, которые вы можете найти на просторах интернета:
-
https://github.com/Freeboard/thingproxy
-
https://github.com/bulletmark/corsproxy
-
https://github.com/Rob—W/cors-anywhere
Перед использованием любого из этих сервисов обязательно проверьте код самой последний версии версии.
Как протестировать CORS?
Использование браузера для проверки конфигурации CORS может оказаться на удивление утомительной задачей. В качестве альтернативы вы можете использовать такие инструменты, как CORS Tester, test-cors.org или, если вас не страшит командная строка, вы можете использовать curl для проверки конфигурации CORS.
curl -v -X OPTIONS https://simplelocalize.io/api/v1/translations
Остерегайтесь ложных CORS-ошибок
В некоторых случаях, когда сервис находится за дополнительным слоем защиты ограничителя частоты запросов, балансировщика нагрузки или сервера авторизации, вы можете получить ложную CORS-ошибку. Заблокированные или отклоненные сервером запросы должны отвечать статус кодами ошибки. Например:
-
401 unauthorized,
-
403 forbidden,
-
429 too many requests,
-
500 internal server error,
-
любые, кроме 2XX или 3XX.
Вы можете видеть, что запрос заблокирован из-за неудачного предварительного запроса, но на самом деле служба просто отклоняет его. Вы всегда должны проверять статус код и текст ответа, чтобы избежать излишней отладки. Браузер должным образом уведомляет вас о сбое в предварительном CORS-запросе, но причина сбоя может быть не связана с конфигурацией CORS.
Заключение
В этой статье я постарался объяснить, что такое CORS и каковы наиболее распространенные проблемы с ним. Я предложил четыре способа избавиться от проблемы с CORS и объяснил преимущества и недостатки каждого из них. Я также объяснил, как правильно настроить CORS-ответы и как их протестировать. Более того, я показал самые распространенные проблемы, с которыми вы можете столкнуться при распознавании ложных CORS-ошибок. Я постарался изложить все максимально простым языком и избежать мудреных технических подробностей. Cпасибо за внимание!
Полезные ссылки
-
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors
-
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
-
https://enable-cors.org/
-
https://stackoverflow.com/a/42024918/1133169
Материал подготовлен в преддверии старта онлайн-курса «JavaScript Developer. Professional». Недавно прошел открытый урок на тему «CSS-in-JS. Удобный способ управлять стилями», на котором рассмотрели Styled components, Linaria, Astroturf и другие инструменты упрощения работы со стилями. Посмотреть запись можно по ссылке.
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a «preflight» request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.
An example of a cross-origin request: the front-end JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json.
For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to mitigate the risks of cross-origin HTTP requests.
What requests use CORS?
This cross-origin sharing standard can enable cross-origin HTTP requests for:
- Invocations of the
XMLHttpRequestor Fetch APIs, as discussed above. - Web Fonts (for cross-domain font usage in
@font-facewithin CSS), so that servers can deploy TrueType fonts that can only be loaded cross-origin and used by web sites that are permitted to do so. - WebGL textures.
- Images/video frames drawn to a canvas using
drawImage(). - CSS Shapes from images.
This is a general article about Cross-Origin Resource Sharing and includes a discussion of the necessary HTTP headers.
Functional overview
The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to read that information from a web browser. Additionally, for HTTP request methods that can cause side-effects on server data (in particular, HTTP methods other than GET, or POST with certain MIME types), the specification mandates that browsers «preflight» the request, soliciting supported methods from the server with the HTTP OPTIONS request method, and then, upon «approval» from the server, sending the actual request. Servers can also inform clients whether «credentials» (such as Cookies and HTTP Authentication) should be sent with requests.
CORS failures result in errors but for security reasons, specifics about the error are not available to JavaScript. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser’s console for details.
Subsequent sections discuss scenarios, as well as provide a breakdown of the HTTP headers used.
Examples of access control scenarios
We present three scenarios that demonstrate how Cross-Origin Resource Sharing works. All these examples use XMLHttpRequest, which can make cross-origin requests in any supporting browser.
Simple requests
Some requests don’t trigger a CORS preflight. Those are called simple requests from the obsolete CORS spec, though the Fetch spec (which now defines CORS) doesn’t use that term.
The motivation is that the <form> element from HTML 4.0 (which predates cross-site XMLHttpRequest and fetch) can submit simple requests to any origin, so anyone writing a server must already be protecting against cross-site request forgery (CSRF). Under this assumption, the server doesn’t have to opt-in (by responding to a preflight request) to receive any request that looks like a form submission, since the threat of CSRF is no worse than that of form submission. However, the server still must opt-in using Access-Control-Allow-Origin to share the response with the script.
A simple request is one that meets all the following conditions:
- One of the allowed methods:
GETHEADPOST
- Apart from the headers automatically set by the user agent (for example,
Connection,User-Agent, or the other headers defined in the Fetch spec as a forbidden header name), the only headers which are allowed to be manually set are those which the Fetch spec defines as a CORS-safelisted request-header, which are:AcceptAccept-LanguageContent-LanguageContent-Type(please note the additional requirements below)Range(only with a simple range header value; e.g.,bytes=256-orbytes=127-255)
Note: Firefox has not implemented Range as a safelisted request-header yet. See bug 1733981.
- The only type/subtype combinations allowed for the media type specified in the
Content-Typeheader are:application/x-www-form-urlencodedmultipart/form-datatext/plain
- If the request is made using an
XMLHttpRequestobject, no event listeners are registered on the object returned by theXMLHttpRequest.uploadproperty used in the request; that is, given anXMLHttpRequestinstancexhr, no code has calledxhr.upload.addEventListener()to add an event listener to monitor the upload. - No
ReadableStreamobject is used in the request.
For example, suppose web content at https://foo.example wishes to invoke content on domain https://bar.other. Code of this sort might be used in JavaScript deployed on foo.example:
const xhr = new XMLHttpRequest();
const url = "https://bar.other/resources/public-data/";
xhr.open("GET", url);
xhr.onreadystatechange = someHandler;
xhr.send();
This operation performs a simple exchange between the client and the server, using CORS headers to handle the privileges:

Let’s look at what the browser will send to the server in this case:
GET /resources/public-data/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Connection: keep-alive
Origin: https://foo.example
The request header of note is Origin, which shows that the invocation is coming from https://foo.example.
Now let’s see how the server responds:
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 00:23:53 GMT
Server: Apache/2
Access-Control-Allow-Origin: *
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/xml
[…XML Data…]
In response, the server returns a Access-Control-Allow-Origin header with Access-Control-Allow-Origin: *, which means that the resource can be accessed by any origin.
Access-Control-Allow-Origin: *
This pattern of the Origin and Access-Control-Allow-Origin headers is the simplest use of the access control protocol. If the resource owners at https://bar.other wished to restrict access to the resource to requests only from https://foo.example (i.e., no domain other than https://foo.example can access the resource in a cross-origin manner), they would send:
Access-Control-Allow-Origin: https://foo.example
Note: When responding to a credentialed requests request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the «*» wildcard.
Preflighted requests
Unlike simple requests, for «preflighted» requests the browser first sends an HTTP request using the OPTIONS method to the resource on the other origin, in order to determine if the actual request is safe to send. Such cross-origin requests are preflighted since they may have implications for user data.
The following is an example of a request that will be preflighted:
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://bar.other/doc");
xhr.setRequestHeader("X-PINGOTHER", "pingpong");
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.onreadystatechange = handler;
xhr.send("<person><name>Arun</name></person>");
The example above creates an XML body to send with the POST request. Also, a non-standard HTTP X-PINGOTHER request header is set. Such headers are not part of HTTP/1.1, but are generally useful to web applications. Since the request uses a Content-Type of text/xml, and since a custom header is set, this request is preflighted.

Note: As described below, the actual POST request does not include the Access-Control-Request-* headers; they are needed only for the OPTIONS request.
Let’s look at the full exchange between client and server. The first exchange is the preflight request/response:
OPTIONS /doc HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Connection: keep-alive
Origin: https://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type
HTTP/1.1 204 No Content
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
Vary: Accept-Encoding, Origin
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Lines 1 — 10 above represent the preflight request with the OPTIONS method. The browser determines that it needs to send this based on the request parameters that the JavaScript code snippet above was using, so that the server can respond whether it is acceptable to send the request with the actual request parameters. OPTIONS is an HTTP/1.1 method that is used to determine further information from servers, and is a safe method, meaning that it can’t be used to change the resource. Note that along with the OPTIONS request, two other request headers are sent (lines 9 and 10 respectively):
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type
The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will do so with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will do so with X-PINGOTHER and Content-Type custom headers. Now the server has an opportunity to determine whether it can accept a request under these conditions.
Lines 12 — 21 above are the response that the server returns, which indicate that the request method (POST) and request headers (X-PINGOTHER) are acceptable. Let’s have a closer look at lines 15-18:
Access-Control-Allow-Origin: https://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
The server responds with Access-Control-Allow-Origin: https://foo.example, restricting access to the requesting origin domain only. It also responds with Access-Control-Allow-Methods, which says that POST and GET are valid methods to query the resource in question (this header is similar to the Allow response header, but used strictly within the context of access control).
The server also sends Access-Control-Allow-Headers with a value of «X-PINGOTHER, Content-Type«, confirming that these are permitted headers to be used with the actual request. Like Access-Control-Allow-Methods, Access-Control-Allow-Headers is a comma-separated list of acceptable headers.
Finally, Access-Control-Max-Age gives the value in seconds for how long the response to the preflight request can be cached without sending another preflight request. The default value is 5 seconds. In the present case, the max age is 86400 seconds (= 24 hours). Note that each browser has a maximum internal value that takes precedence when the Access-Control-Max-Age exceeds it.
Once the preflight request is complete, the real request is sent:
POST /doc HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Connection: keep-alive
X-PINGOTHER: pingpong
Content-Type: text/xml; charset=UTF-8
Referer: https://foo.example/examples/preflightInvocation.html
Content-Length: 55
Origin: https://foo.example
Pragma: no-cache
Cache-Control: no-cache
<person><name>Arun</name></person>
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:40 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://foo.example
Vary: Accept-Encoding, Origin
Content-Encoding: gzip
Content-Length: 235
Keep-Alive: timeout=2, max=99
Connection: Keep-Alive
Content-Type: text/plain
[Some XML payload]
Preflighted requests and redirects
Not all browsers currently support following redirects after a preflighted request. If a redirect occurs after such a request, some browsers currently will report an error message such as the following:
The request was redirected to ‘https://example.com/foo’, which is disallowed for cross-origin requests that require preflight.
Request requires preflight, which is disallowed to follow cross-origin redirects.
The CORS protocol originally required that behavior but was subsequently changed to no longer require it. However, not all browsers have implemented the change, and thus still exhibit the originally required behavior.
Until browsers catch up with the spec, you may be able to work around this limitation by doing one or both of the following:
- Change the server-side behavior to avoid the preflight and/or to avoid the redirect
- Change the request such that it is a simple request that doesn’t cause a preflight
If that’s not possible, then another way is to:
- Make a simple request (using
Response.urlfor the Fetch API, orXMLHttpRequest.responseURL) to determine what URL the real preflighted request would end up at. - Make another request (the real request) using the URL you obtained from
Response.urlorXMLHttpRequest.responseURLin the first step.
However, if the request is one that triggers a preflight due to the presence of the Authorization header in the request, you won’t be able to work around the limitation using the steps above. And you won’t be able to work around it at all unless you have control over the server the request is being made to.
Requests with credentials
Note: When making credentialed requests to a different domain, third-party cookie policies will still apply. The policy is always enforced regardless of any setup on the server and the client as described in this chapter.
The most interesting capability exposed by both XMLHttpRequest or Fetch and CORS is the ability to make «credentialed» requests that are aware of HTTP cookies and HTTP Authentication information. By default, in cross-origin XMLHttpRequest or Fetch invocations, browsers will not send credentials. A specific flag has to be set on the XMLHttpRequest object or the Request constructor when it is invoked.
In this example, content originally loaded from https://foo.example makes a simple GET request to a resource on https://bar.other which sets Cookies. Content on foo.example might contain JavaScript like this:
const invocation = new XMLHttpRequest();
const url = "https://bar.other/resources/credentialed-content/";
function callOtherDomain() {
if (invocation) {
invocation.open("GET", url, true);
invocation.withCredentials = true;
invocation.onreadystatechange = handler;
invocation.send();
}
}
Line 7 shows the flag on XMLHttpRequest that has to be set in order to make the invocation with Cookies, namely the withCredentials boolean value. By default, the invocation is made without Cookies. Since this is a simple GET request, it is not preflighted but the browser will reject any response that does not have the Access-Control-Allow-Credentials: true header, and not make the response available to the invoking web content.

Here is a sample exchange between client and server:
GET /resources/credentialed-content/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Connection: keep-alive
Referer: https://foo.example/examples/credential.html
Origin: https://foo.example
Cookie: pageAccess=2
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:34:52 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://foo.example
Access-Control-Allow-Credentials: true
Cache-Control: no-cache
Pragma: no-cache
Set-Cookie: pageAccess=3; expires=Wed, 31-Dec-2008 01:34:53 GMT
Vary: Accept-Encoding, Origin
Content-Encoding: gzip
Content-Length: 106
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain
[text/plain payload]
Although line 10 contains the Cookie destined for the content on https://bar.other, if bar.other did not respond with an Access-Control-Allow-Credentials: true (line 16), the response would be ignored and not made available to the web content.
Preflight requests and credentials
CORS-preflight requests must never include credentials. The response to a preflight request must specify Access-Control-Allow-Credentials: true to indicate that the actual request can be made with credentials.
Note: Some enterprise authentication services require that TLS client certificates be sent in preflight requests, in contravention of the Fetch specification.
Firefox 87 allows this non-compliant behavior to be enabled by setting the preference: network.cors_preflight.allow_client_cert to true (bug 1511151). Chromium-based browsers currently always send TLS client certificates in CORS preflight requests (Chrome bug 775438).
Credentialed requests and wildcards
When responding to a credentialed request:
- The server must not specify the «
*» wildcard for theAccess-Control-Allow-Originresponse-header value, but must instead specify an explicit origin; for example:Access-Control-Allow-Origin: https://example.com - The server must not specify the «
*» wildcard for theAccess-Control-Allow-Headersresponse-header value, but must instead specify an explicit list of header names; for example,Access-Control-Allow-Headers: X-PINGOTHER, Content-Type - The server must not specify the «
*» wildcard for theAccess-Control-Allow-Methodsresponse-header value, but must instead specify an explicit list of method names; for example,Access-Control-Allow-Methods: POST, GET - The server must not specify the «
*» wildcard for theAccess-Control-Expose-Headersresponse-header value, but must instead specify an explicit list of header names; for example,Access-Control-Expose-Headers: Content-Encoding, Kuma-Revision
If a request includes a credential (most commonly a Cookie header) and the response includes an Access-Control-Allow-Origin: * header (that is, with the wildcard), the browser will block access to the response, and report a CORS error in the devtools console.
But if a request does include a credential (like the Cookie header) and the response includes an actual origin rather than the wildcard (like, for example, Access-Control-Allow-Origin: https://example.com), then the browser will allow access to the response from the specified origin.
Also note that any Set-Cookie response header in a response would not set a cookie if the Access-Control-Allow-Origin value in that response is the «*» wildcard rather an actual origin.
Third-party cookies
Note that cookies set in CORS responses are subject to normal third-party cookie policies. In the example above, the page is loaded from foo.example but the cookie on line 19 is sent by bar.other, and would thus not be saved if the user’s browser is configured to reject all third-party cookies.
Cookie in the request (line 10) may also be suppressed in normal third-party cookie policies. The enforced cookie policy may therefore nullify the capability described in this chapter, effectively preventing you from making credentialed requests whatsoever.
Cookie policy around the SameSite attribute would apply.
This section lists the HTTP response headers that servers return for access control requests as defined by the Cross-Origin Resource Sharing specification. The previous section gives an overview of these in action.
Access-Control-Allow-Origin
A returned resource may have one Access-Control-Allow-Origin header with the following syntax:
Access-Control-Allow-Origin: <origin> | *
Access-Control-Allow-Origin specifies either a single origin which tells browsers to allow that origin to access the resource; or else — for requests without credentials — the «*» wildcard tells browsers to allow any origin to access the resource.
For example, to allow code from the origin https://mozilla.org to access the resource, you can specify:
Access-Control-Allow-Origin: https://mozilla.org
Vary: Origin
If the server specifies a single origin (that may dynamically change based on the requesting origin as part of an allowlist) rather than the «*» wildcard, then the server should also include Origin in the Vary response header to indicate to clients that server responses will differ based on the value of the Origin request header.
The Access-Control-Expose-Headers header adds the specified headers to the allowlist that JavaScript (such as getResponseHeader()) in browsers is allowed to access.
Access-Control-Expose-Headers: <header-name>[, <header-name>]*
For example, the following:
Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header
…would allow the X-My-Custom-Header and X-Another-Custom-Header headers to be exposed to the browser.
Access-Control-Max-Age
The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached. For an example of a preflight request, see the above examples.
Access-Control-Max-Age: <delta-seconds>
The delta-seconds parameter indicates the number of seconds the results can be cached.
Access-Control-Allow-Credentials
The Access-Control-Allow-Credentials header indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple GET requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content.
Access-Control-Allow-Credentials: true
Credentialed requests are discussed above.
Access-Control-Allow-Methods
The Access-Control-Allow-Methods header specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. The conditions under which a request is preflighted are discussed above.
Access-Control-Allow-Methods: <method>[, <method>]*
An example of a preflight request is given above, including an example which sends this header to the browser.
The Access-Control-Allow-Headers header is used in response to a preflight request to indicate which HTTP headers can be used when making the actual request. This header is the server side response to the browser’s Access-Control-Request-Headers header.
Access-Control-Allow-Headers: <header-name>[, <header-name>]*
This section lists headers that clients may use when issuing HTTP requests in order to make use of the cross-origin sharing feature. Note that these headers are set for you when making invocations to servers. Developers using cross-origin XMLHttpRequest capability do not have to set any cross-origin sharing request headers programmatically.
Origin
The Origin header indicates the origin of the cross-origin access request or preflight request.
The origin is a URL indicating the server from which the request is initiated. It does not include any path information, only the server name.
Note: The origin value can be null.
Note that in any access control request, the Origin header is always sent.
Access-Control-Request-Method
The Access-Control-Request-Method is used when issuing a preflight request to let the server know what HTTP method will be used when the actual request is made.
Access-Control-Request-Method: <method>
Examples of this usage can be found above.
The Access-Control-Request-Headers header is used when issuing a preflight request to let the server know what HTTP headers will be used when the actual request is made (such as with setRequestHeader()). This browser-side header will be answered by the complementary server-side header of Access-Control-Allow-Headers.
Access-Control-Request-Headers: <field-name>[, <field-name>]*
Examples of this usage can be found above.
Specifications
| Specification |
|---|
| Fetch Standard # http-access-control-allow-origin |
Browser compatibility
BCD tables only load in the browser
See also
Cross-Origin Resource Sharing (CORS) is a mechanism based on HTTP headers that allows browsers to identify which request comes from allowed domain list, at the same time filter out unknown requests. Browsers make a “preflight” request to the server hosting the cross-origin resource in order to check that the server will permit the actual request. In that preflight, the browser sends information about the HTTP method and headers that will be used later in the actual request.
Fetching data from sites and APIs that enforced CORS policy without proper headers can lead to “Access to XMLHttpRequest has been blocked by CORS policy” error message in Chrome DevTools. The error comes in several forms, include useful information for debugging.
This article is going to show you how to fix “Access to XMLHttpRequest has been blocked by CORS policy” in various scenarios.
Just as what Chrome DevTools says, “No ‘Access-Control-Allow-Origin’ header is present on the requested response” error means the response does not have the proper Access-Control-Allow-Origin header in place.
In this case, you have a few options :
-
Use a Chrome extension to add
Access-Control-Allow-Originheader into every response.To find one of them, just head over to Chrome Webstore and type in “CORS”, dozens will show up in the search result. Or you can install CORS Helper, CORS Unblock or dyna CORS right away.
-
Redirect your request through a CORS proxy.
You can easily spin up your own proxy using open source code from https://github.com/Rob–W/cors-anywhere/. Deploying to Heroku takes only 2-3 minutes, or you can use the original developers demo for quick, one-time usage : https://cors-anywhere.herokuapp.com/.
To use the proxy, you have to prefix your request URL with the proxy URL so that it would look like this : https://cors-anywhere.herokuapp.com/https://example.com. The proxy will then forward your request to the original server, then grabs the response, adds
Access-Control-Allow-Originheader to the response before pass it to you.
Access to XMLHttpRequest has been blocked by CORS policy : Response to preflight request doesn’t pass access control check
“Response to preflight request doesn’t pass access control check” can comes with additional message about the actual error. If you encounter one of these, you may consider my recommended options in the next section.
The Access-Control-Allow-Origin header doesn’t allow for more than one origin to be specified by design. If you are a fellow web developer, my advice is to carefully review your code that involves setting up CORS headers. You may set the Access-Control-Allow-Origin twice, or adds too many values to it instead of replacing the value. Most of the time, the error is related to the source code.
If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled
An opaque response is for a request made for a resource on a different origin that doesn’t return CORS headers. With an opaque response we won’t be able to read the data returned or view the status of the request, meaning we can’t check if the request was successful or not.
In this situation, you need to modify your code so that the request to the different origin does not contain CORS headers. In JavaScript, the behaviour can be achieved by passing {mode: 'no-cors'} in fetch:
Code language: JavaScript (javascript)
fetch('http://some-site.com/cors-disabled/some.json', {mode: 'no-cors'})
Opaque responses can’t be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch event handler in a service worker. So they’re useful for resources that you can’t control (e.g. resources on a CORS-less CDN) but still want to cache.
For a request that includes credentials, browsers won’t let your front-end JavaScript code access the response if the value of the Access-Control-Allow-Origin response header is set to *. Instead, the value of the header must exactly match your front-end origin, e.g http://where_you_send_request.com.
If you are using any “Easy CORS” Chrome extension like Allow CORS: Access-Control-Allow-Origin or CORS Unblock, disable it and the problem should disappear.
If you have access to the server, you can configure the server to grab the value of the Origin header the client sends, then echo it back to Access-Control-Allow-Origin response header. In nginx configuration language, the setting can be set by placing the line below into the config file.
Code language: PHP (php)
add_header Access-Control-Allow-Origin $http_origin
You can find more details at Credentialed requests and wildcards in the MDN HTTP access control (CORS) article.
Published 2022-07-08
When you send an HTTP request with a different domain than your page’s domain (or IP address + port number), a CORS error will occur. A CORS error means that the API server rejected your request. To access other domain API from your web page, the backend server you requested must set some CORS headers in the HTTP response to allow CORS requests. Below are some errors caused by incorrectly set HTTP response headers for CORS requests.
Error information in web browser console
1 |
Access to XMLHttpRequest at 'http://localhost:8081/api' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. |
Solutions
First, check that the URL, Method, and Content-Type you requested are correct.
Make sure the server API is up and running.
Enable CORS requests for your server API. Add Access-Control-Allow-Origin in HTTP response header.
1 |
Access-Control-Allow-Origin: * |
For example, in Java web projects.
1 |
response.setHeader("Access-Control-Allow-Origin", "*"); |
Reasons
The API is not shared with other origins. You need to update the API CORS policy by set Access-Control-Allow-Origin in response headers.
Error: Method xxx is not allowed
Error information in web browser console
1 |
Access to XMLHttpRequest at 'http://localhost:8081/api/delete' from origin 'http://localhost' has been blocked by CORS policy: Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response. |
Solutions
Add Access-Control-Allow-Methods: {method_name_in_error_message} in HTTP response header. Note that method names must be capitalized.
For example, in Java web projects.
1 |
response.setHeader("Access-Control-Allow-Methods", "DELETE"); |
Reasons
The default allowed HTTP methods for CORS are GET, POST, and HEAD. For other HTTP methods like DELETE or PUT, you need to add it to HTTP response header Access-Control-Allow-Methods.
Error information in web browser console
1 |
Access to XMLHttpRequest at 'http://localhost:8081/api/delete' from origin 'http://localhost' has been blocked by CORS policy: Request header field my-header1 is not allowed by Access-Control-Allow-Headers in preflight response. |
1 |
Access to XMLHttpRequest at 'http://localhost:8081/api/get?name=Jack' from origin 'http://localhost' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. |
Solutions
Add Access-Control-Allow-Headers: {header_field_name_in_error_message} in HTTP response header.
For example, in Java web projects.
1 |
response.setHeader("Access-Control-Allow-Headers", "my-header1"); |
Reasons
The default allowed HTTP headers for CORS requests are:
- Accept
- Accept-Language
- Content-Language
- Content-Type (value only be application/x-www-form-urlencoded, multipart/form-data, or text/plain)
- Range
For other HTTP headers, you need to add them to HTTP response header Access-Control-Allow-Headers.
Error information in web browser console
1 |
Access to XMLHttpRequest at 'http://localhost:8081/api/get' from origin 'http://localhost' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. |
Solutions
Set the value of Access-Control-Allow-Origin to your page domain instead of * in HTTP response header. And set the value of Access-Control-Allow-Credentials to true.
For example, in Java web projects.
1 |
response.setHeader("Access-Control-Allow-Origin", "http://localhost"); |
Reasons
When you send a CORS request with credentials, you must set a specific domain in Access-Control-Allow-Origin.
CORS request with credentials: withCredentials: true
1 |
const xhr = new XMLHttpRequest(); |
1 |
$.ajax({ |
Error information in web browser console
1 |
Access to XMLHttpRequest at 'http://localhost:8081/api/get' from origin 'http://localhost' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. |
Solutions
Add Access-Control-Allow-Credentials: true in HTTP response header.
For example, in Java web projects.
1 |
response.setHeader("Access-Control-Allow-Credentials", "true"); |
Reasons
When the request’s credentials flag is true, the HTTP response header Access-Control-Allow-Credentials should be true.
Many websites have JavaScript functions that make network requests to a server, such as a REST API. The web pages and APIs are often in different domains. This introduces security issues in that any website can request data from an API. Cross-Origin Resource Sharing (CORS) provides a solution to these issues. It became a W3C recommendation in 2014. It makes it the responsibility of the web browser to prevent unauthorized access to APIs. All modern web browsers enforce CORS. They prevent JavaScript from obtaining data from a server in a domain different than the domain the website was loaded from, unless the REST API server gives permission.
From a developer’s perspective, CORS is often a cause of much grief when it blocks network requests. CORS provides a number of different mechanisms for limiting JavaScript access to APIs. It is often not obvious which mechanism is blocking the request. We are going to build a simple web application that makes REST calls to a server in a different domain. We will deliberately make requests that the browser will block because of CORS policies and then show how to fix the issues. Let’s get started!
NOTE: The code for this project can be found on GitHub.
Table of Contents
- Prerequisites to Building a Go Application
- How to Build a Simple Web Front End
- How to Build a Simple REST API in Go
- How to Solve a Simple CORS Issue
- Allowing Access from Any Origin Domain
- CORS in Flight
- What Else Does CORS Block?
- Restrictions on Response Headers
- Credentials Are a Special Case
- Control CORS Cache Configuration
- How to Prevent CORS Issues with Okta
- How CORS Prevents Security Issues
Prerequisites to Building a Go Application
First things first, if you don’t already have Go installed on your computer you will need to download and install the Go Programming Language.
Now, create a directory where all of our future code will live.
Finally, we will make our directory a Go module and install the Gin package (a Go web framework) to implement a web server.
go mod init cors
go get github.com/gin-gonic/gin
go get github.com/gin-contrib/static
A file called go.mod will get created containing the dependencies.
How to Build a Simple Web Front End
We are going to build a simple HTML and JavaScript front end and serve it from a web server written using Gin.
First of all, create a directory called frontend and create a file called frontend/index.html with the following content:
<html>
<head>
<meta charset="UTF-8" />
<title>Fixing Common Issues with CORS</title>
</head>
<body>
<h1>Fixing Common Issues with CORS</h1>
<div>
<textarea id="messages" name="messages" rows="10" cols="50">Messages</textarea><br/>
<form id="form1">
<input type="button" value="Get v1" onclick="onGet('v1')"/>
<input type="button" value="Get v2" onclick="onGet('v2')"/>
</form>
</div>
</body>
</html>
The web page has a text area to display messages and a simple form with two buttons. When a button is clicked it calls the JavaScript function onGet() passing it a version number. The idea being that v1 requests will always fail due to CORS issues, and v2 will fix the issue.
Next, create a file called frontend/control.js containing the following JavaScript:
function onGet(version) {
const url = "http://localhost:8000/api/" + version + "/messages";
var headers = {}
fetch(url, {
method : "GET",
mode: 'cors',
headers: headers
})
.then((response) => {
if (!response.ok) {
throw new Error(response.error)
}
return response.json();
})
.then(data => {
document.getElementById('messages').value = data.messages;
})
.catch(function(error) {
document.getElementById('messages').value = error;
});
}
The onGet() function inserts the version number into the URL and then makes a fetch request to the API server. A successful request will return a list of messages. The messages are displayed in the text area.
Finally, create a file called frontend/.go containing the following Go code:
package main
import (
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.Use(static.Serve("/", static.LocalFile("./frontend", false)))
r.Run(":8080")
}
This code simply serves the contents of the frontend directory on requests on port 8080. Note that JavaScript makes a call to port http://localhost:8000 which is a separate service.
Start the server and point a web browser at http://localhost:8080 to see the static content.
How to Build a Simple REST API in Go
Create a directory called rest to contain the code for a basic REST API.
NOTE: A separate directory is required as Go doesn’t allow two program entry points in the same directory.
Create a file called rest/server.go containing the following Go code:
package main
import (
"fmt"
"strconv"
"net/http"
"github.com/gin-gonic/gin"
)
var messages []string
func GetMessages(c *gin.Context) {
version := c.Param("version")
fmt.Println("Version", version)
c.JSON(http.StatusOK, gin.H{"messages": messages})
}
func main() {
messages = append(messages, "Hello CORS!")
r := gin.Default()
r.GET("/api/:version/messages", GetMessages)
r.Run(":8000")
}
A list called messages is created to hold message objects.
The function GetMessages() is called whenever a GET request is made to the specified URL. It returns a JSON string containing the messages. The URL contains a path parameter which will be v1 or v2. The server listens on port 8000.
The server can be run using:
How to Solve a Simple CORS Issue
We now have two servers—the front-end one on http://localhost:8080, and the REST API server on http://localhost:8000. Even though the two servers have the same hostname, the fact that they are listening on different port numbers puts them in different domains from the CORS perspective. The domain of the web content is referred to as the origin. If the JavaScript fetch request specifies cors a request header will be added identifying the origin.
Origin: http://localhost:8080
Make sure both the frontend and REST servers are running.
Next, point a web browser at http://localhost:8080 to display the web page. We are going to get JavaScript errors, so open your browser’s developer console so that we can see what is going on. In Chrome it is *View** > Developer > Developer Tools.
Next, click on the Send v1 button. You will get a JavaScript error displayed in the console:
Access to fetch at ‘http://localhost:8000/api/v1/messages’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
The message says that the browser has blocked the request because of a CORS policy. It suggests two solutions. The second suggestion is to change the mode from cors to no-cors in the JavaScript fetch request. This is not an option as the browser always deletes the response data when in no-cors mode to prevent data from being read by an unauthorized client.
The solution to the issue is for the server to set a response header that allows the browser to make cross-domain requests to it.
Access-Control-Allow-Origin: http://localhost:8080
This tells the web browser that the cross-origin requests are to be allowed for the specified domain. If the domain specified in the response header matches the domain of the web page, specified in the Origin request header, then the browser will not block the response being received by JavaScript.
We are going to set the header when the URL contains v2. Change the GetMessages() function in cors/server.go to the following:
func GetMessages(c *gin.Context) {
version := c.Param("version")
fmt.Println("Version", version)
if version == "v2" {
c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
}
c.JSON(http.StatusOK, gin.H{"messages": messages})
}
This sets a header to allow cross-origin requests for the v2 URI.
Restart the server and go to the web page. If you click on Get v1 you will get blocked by CORS. If you click on Get v2, the request will be allowed.
A response can only have at most one Access-Control-Allow-Origin header. The header can only specify only one domain. If the server needs to allow requests from multiple origin domains, it needs to generate an Access-Control-Allow-Origin response header with the same value as the Origin request header.
Allowing Access from Any Origin Domain
There is an option to prevent CORS from blocking any domain. This is very popular with developers!
Access-Control-Allow-Origin: *
Be careful when using this option. It will get flagged in a security audit. It may also be in violation of an information security policy, which could have serious consequences!
CORS in Flight
Although we have fixed the main CORS issue, there are some limitations. One of the limitations is that only the HTTP GET, and OPTIONS methods are allowed. The GET and OPTIONS methods are read-only and are considered safe as they don’t modify existing content. The POST, PUT, and DELETE methods can add or change existing content. These are considered unsafe. Let’s see what happens when we make a PUT request.
First of all, add a new form to client/index.html:
<form id="form2">
<input type="text" id="puttext" name="puttext"/>
<input type="button" value="Put v1" onclick="onPut('v1')"/>
<input type="button" value="Put v2" onclick="onPut('v2')"/>
</form>
This form has a text input and the two send buttons as before that call a new JavaScript function.
Next, add the JavaScript funtion to client/control.js:
function onPut(version) {
const url = "http://localhost:8000/api/" + version + "/messages/0";
var headers = {}
fetch(url, {
method : "PUT",
mode: 'cors',
headers: headers,
body: new URLSearchParams(new FormData(document.getElementById("form2"))),
})
.then((response) => {
if (!response.ok) {
throw new Error(response.error)
}
return response.json();
})
.then(data => {
document.getElementById('messages').value = data.messages;
})
.catch(function(error) {
document.getElementById('messages').value = error;
});
}
This makes a PUT request sending the form parameters in the request body. Note that the URI ends in /0. This means that the request is to create or change the message with the identifier 0.
Next, define a PUT handler in the main() function of rest/server.go:
r.PUT("/api/:version/messages/:id", PutMessage)
The message identifier is extracted as a path parameter.
Finally, add the request handler function to rest/server.go:
func PutMessage(c *gin.Context) {
version := c.Param("version")
id, _ := strconv.Atoi(c.Param("id"))
text := c.PostForm("puttext")
messages[id] = text
if version == "v2" {
c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
}
c.JSON(http.StatusOK, gin.H{"messages": messages})
}
This updates the message from the form data and sends the new list of messages. The function also always sets the allow origin header, as we know that it is required.
Now, restart the servers and load the web page. Make sure that the developer console is open. Add some text to the text input and hit the Send v1 button.
You will see a slightly different CORS error in the console:
Access to fetch at ‘http://localhost:8000/api/v1/messages/0’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
This is saying that a preflight check was made, and that it didn’t set the Access-Control-Allow-Origin header.
Now, look at the console output from the API server:
[GIN] 2020/12/01 - 11:10:09 | 404 | 447ns | ::1 | OPTIONS "/api/v1/messages/0"
So, what is happening here? JavaScript is trying to make a PUT request. This is not allowed by CORS policy. In the GET example, the browser made the request and blocked the response. In this case, the browser refuses to make the PUT request. Instead, it sent an OPTIONS request to the same URI. It will only send the PUT if the OPTIONS request returns the correct CORS header. This is called a preflight request. As the server doesn’t know what method the OPTIONS preflight request is for, it specifies the method in a request header:
Access-Control-Request-Method: PUT
Let’s fix this by adding a handler for the OPTIONS request that sets the allow origin header in cors/server.go:
func OptionMessage(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
}
func main() {
messages = append(messages, "Hello CORS!")
r := gin.Default()
r.GET("/api/:version/messages", GetMessages)
r.PUT("/api/:version/messages/:id", PutMessage)
r.OPTIONS("/api/v2/messages/:id", OptionMessage)
r.Run(":8000")
}
Notice that the OPTIONS handler is only set for the v2 URI as we don’t want to fix v1.
Now, restart the server and send a message using the Put v2 button. We get yet another CORS error!
Access to fetch at ‘http://localhost:8000/api/v2/messages/0’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
This is saying that the preflight check needs another header to stop the PUT request from being blocked.
Add the response header to cors/server.go:
func OptionMessage(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
c.Header("Access-Control-Allow-Methods", "GET, OPTIONS, POST, PUT")
}
Restart the server and resend the message. The CORS issues are resolved.
What Else Does CORS Block?
CORS has a very restrictive policy regarding which HTTP request headers are allowed. It only allows safe listed request headers. These are Accept, Accept-Language, Content-Language, and Content-Type. They can only contain printable characters and some punctuation characters are not allowed. Header values can’t have more than 128 characters.
There are further restrictions on the Content-Type header. It can only be one of application/x-www-form-urlencoded, multipart/form-data, and text/plain. It is interesting to note that application/json is not allowed.
Let’s see what happens if we send a custom request header. Modify the onPut() function in frontend/control.jsto set a header:
var headers = { "X-Token": "abcd1234" }
Now, make sure that the servers are running and load or reload the web page. Type in a message and click the Put v1 button. You will see a CORS error in the developer console.
Access to fetch at ‘http://localhost:8000/api/v2/messages/0’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Request header field x-token is not allowed by Access-Control-Allow-Headers in preflight response.
Any header which is not CORS safe-listed causes a preflight request. This also contains a request header that specifies the header that needs to be allowed:
Access-Control-Request-Headers: x-token
Note that the header name x-token is specified in lowercase.
The preflight response can allow non-safe-listed headers and can remove restrictions on safe listed headers:
Access-Control-Allow-Headers: X_Token, Content-Type
Next, change the function in cors/server.go to allow the custom header:
func OptionMessage(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT")
c.Header("Access-Control-Allow-Headers", "X-Token")
}
Restart the server and resend the message by clicking the Put v2 button. The request should now be successful.
CORS also places restrictions on response headers. There are seven whitelisted response headers: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified, and Pragma. These are the only response headers that can be accessed from JavaScript. Let’s see this in action.
First of all, add a text area to frontend/index.html to display the headers:
<textarea id="headers" name="headers" rows="10" cols="50">Headers</textarea><br/>
Next, replace the first then block in the onPut function in frontend/control.js to display the response headers:
.then((response) => {
if (!response.ok) {
throw new Error(response.error)
}
response.headers.forEach(function(val, key) {
document.getElementById('headers').value += 'n' + key + ': ' + val;
});
return response.json();
})
Finally, set a custom header in rest/server.go:
func PutMessage(c *gin.Context) {
version := c.Param("version")
id, _ := strconv.Atoi(c.Param("id"))
text := c.PostForm("puttext")
messages[id] = text
if version == "v2" {
c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
}
c.Header("X-Custom", "123456789")
c.JSON(http.StatusOK, gin.H{"messages": messages})
}
Now, restart the server and reload the web page. Type in a message and hit Put v2. You should see some headers displayed, but not the custom header. CORS has blocked it.
This can be fixed by setting another response header to expose the custom header in server/server.go:
func PutMessage(c *gin.Context) {
version := c.Param("version")
id, _ := strconv.Atoi(c.Param("id"))
text := c.PostForm("puttext")
messages[id] = text
if version == "v2" {
c.Header("Access-Control-Expose-Headers", "X-Custom")
c.Header("Access-Control-Allow-Origin", "http://localhost:8080")
}
c.Header("X-Custom", "123456789")
c.JSON(http.StatusOK, gin.H{"messages": messages})
}
Restart the server and reload the web page. Type in a message and hit Put v2. You should see some headers displayed, including the custom header. CORS has now allowed it.
Credentials Are a Special Case
There is yet another CORS blocking scenario. JavaScript has a credentials request mode. This determines how user credentials, such as cookies are handled. The options are:
omit: Never send or receive cookies.same-origin: This is the default, that allows user credentials to be sent to the same origin.include: Send user credentials even if cross-origin.
Let’s see what happens.
Modify the fetch call in the onPut() function in frontend/Control.js:
fetch(url, {
method : "PUT",
mode: 'cors',
credentials: 'include',
headers: headers,
body: new URLSearchParams(new FormData(document.getElementById("form2"))),
})
Now, make sure that the client and server are running and reload the web page. Send a message as before. You will get another CORS error in the developer console:
Access to fetch at ‘http://localhost:8000/api/v2/messages/0’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’.
The fix for this is to add another header to both the OptionMessage(), and PutMessage() functions in cors/server.go as the header needs to be present in both the preflight request and the actual request:
c.Header("Access-Control-Allow-Credentials", "true")
The request should now work correctly.
The credentials issue can also be resolved on the client by setting the credentials mode to omit and sending credentials as request parameters, instead of using cookies.
Control CORS Cache Configuration
The is one more CORS header that hasn’t yet been discussed. The browser can cache the preflight request results. The Access-Control-Max-Age header specifies the maximum time, in seconds, the results can be cached. It should be added to the preflight response headers as it controls how long the Access-Control-Allow-Methods and Access-Control-Allow-Headers results can be cached.
Access-Control-Max-Age: 600
Browsers typically have a cap on the maximum time. Setting the time to -1 prevents caching and forces a preflight check on all calls that require it.
How to Prevent CORS Issues with Okta
Authentication providers, such as Okta, need to handle cross-domain requests to their authentication servers and API servers. This is done by providing a list of trusted origins. See Okta Enable CORS for more information.
How CORS Prevents Security Issues
CORS is an important security feature that is designed to prevent JavaScript clients from accessing data from other domains without authorization.
Modern web browsers implement CORS to block cross-domain JavaScript requests by default. The server needs to authorize cross-domain requests by setting the correct response headers.
CORS has several layers. Simply allowing an origin domain only works for a subset of request methods and request headers. Some request methods and headers force a preflight request as a further means of protecting data. The actual request is only allowed if the preflight response headers permit it.
CORS is a major pain point for developers. If a request is blocked, it is not easy to understand why, and how to fix it. An understanding of the nature of the blocked request, and of the CORS mechanisms, can easily overcome such issues.
If you enjoyed this post, you might like related ones on this blog:
- What is the OAuth 2.0 Implicit Grant Type?
- Combat Side-Channel Attacks with Cross-Origin Read Blocking
Follow us for more great content and updates from our team! You can find us on Twitter, Facebook, subscribe to our YouTube Channel or start the conversation below.










