Kors отключить в браузере firefox

Обновлено: 07.07.2024

In Firefox, how do I do the equivalent of --disable-web-security in Chrome. This has been posted a lot, but never a true answer. Most are links to add-ons (some of which don't work in the latest Firefox or don't work at all) and "you just need to enable support on the server".

Again, this is only for testing before pushing to prod which, then, would be on an allowable domain.


29.2k 40 40 gold badges 105 105 silver badges 195 195 bronze badges @TanMaiVan Your addon did not worked for me on Firefox. @KhadoMikhal Thanks for the report. I will check and fix it soon.

8 Answers 8

For me, none of these seem to have any effect.

This comment implies there is no built-in way in Firefox to do this (as of 2/8/14).

12.9k 10 10 gold badges 69 69 silver badges 113 113 bronze badges security.fileuri.strict_origin_policy helps when one needs to get the content of one local file through AJAX into another and the first one is not in the same folder (or in subfolder of that folder) as the second one. 3,730 2 2 gold badges 32 32 silver badges 37 37 bronze badges


enter image description here

Just fixed the bug and the add on working again now. Works for me! I allowed CORS for localhost and now I can test my web apps and APIs locally without setting up complicated servers. Thank you! Very handy , I wish if u could add support for subdomains, Thank u 🌹.

The Chrome setting you refer to is to disable the same origin policy.

This was covered in this thread also: Disable firefox same origin policy

about:config -> security.fileuri.strict_origin_policy -> false

setting this setting to false did not have any effect; the requests are still stuck on OPTIONS This just changes file:// URI policy, not the one needed This answer fixed the font-awesome download failed issue I was having on my local dev environment from a cross-origin restriction.

You can even configure it by Referrers (Website).


I have not been able to find a Firefox option equivalent of --disable-web-security or an addon that does that for me. I really needed it for some testing scenarios where modifying the web server was not possible. What did help was to use Fiddler to auto-modify web responses so that they have the correct headers and CORS is no longer an issue.

Go to menu Rules -> Customize rules. Modify the OnBeforeResponseFunction so that it looks like the following, then save:

This will make every web response to have the Access-Control-Allow-Origin: * header.


Who should read this article?

More specifically, this article is for web administrators, server developers and front-end developers. Modern browsers handle the client side of cross-origin sharing, including headers and policy enforcement. But the CORS standard means servers have to handle new request and response headers.

What requests use CORS?

Functional overview

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.

Examples of access control scenarios

Simple requests

Some requests don't trigger a CORS preflight. Those are called simple requests, though the Fetch spec (which defines CORS) doesn't use that term. A simple request is one that meets all the following conditions:

  • One of the allowed methods:
  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Note: WebKit Nightly and Safari Technology Preview place additional restrictions on the values allowed in the Accept , Accept-Language , and Content-Language headers. If any of those headers have "nonstandard" values, WebKit/Safari does not consider the request to be a "simple request". What values WebKit/Safari consider "nonstandard" is not documented, except in the following WebKit bugs:

No other browsers implement these extra restrictions because they're not part of the spec.

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, and let's see how the server responds:

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.

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

The following is an example of a request that will be 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:

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 13 - 22 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 16-19:

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:

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 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:

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.


Here is a sample exchange between client and server:

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 the Access-Control-Allow-Origin response-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 the Access-Control-Allow-Headers response-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 the Access-Control-Allow-Methods response-header value, but must instead specify an explicit list of method names; for example, Access-Control-Allow-Methods: POST, GET

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.

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.

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.

Access-Control-Allow-Origin

A returned resource may have one Access-Control-Allow-Origin header with the following syntax:

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.

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.

Access-Control-Expose-Headers

The Access-Control-Expose-Headers header adds the specified headers to the allowlist that JavaScript (such as getResponseHeader() ) in browsers is allowed to access.

For example, the following:

…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.

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-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.

An example of a preflight request is given above, including an example which sends this header to the browser.

Access-Control-Allow-Headers

Origin

The Origin header indicates the origin of the cross-site 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

Examples of this usage can be found above.

Access-Control-Request-Headers

Is there any way to disable the Same-origin policy on Google's Chrome browser?


7,367 8 8 gold badges 50 50 silver badges 80 80 bronze badges 63.9k 42 42 gold badges 102 102 silver badges 130 130 bronze badges See also peter.sh/experiments/chromium-command-line-switches, I am not sure of its authenticity but it appears to be a collection produced by an automated process Since version 49, use this option --disable-web-security --user-data-dir

35 Answers 35

Close chrome (or chromium) and restart with the --disable-web-security argument. I just tested this and verified that I can access the contents of an iframe with src="http://google.com/" embedded in a page served from "localhost" (tested under chromium 5 / ubuntu). For me the exact command was:

Note : Kill all chrome instances before running command

The browser will warn you that "you are using an unsupported command line" when it first opens, which you can ignore.

From the chromium source:

Before Chrome 48, you could just use:

148k 45 45 gold badges 317 317 silver badges 488 488 bronze badges 70.4k 18 18 gold badges 104 104 silver badges 138 138 bronze badges As of latest versions of chrome (e.g. I have version 92), "--disable-web-security" is necessary but not enough. It is also required to use "--disable-site-isolation-trials". See the more recent answer from @user2576266 below. (Note that chrome will still display a warning that "--disable-site-isolation-trials" is not understood. It actually works.) @AliNakisaee I have version 95, but "--disable-site-isolation-trials" does not work.

Yep. For OSX, open Terminal and run:

Also if you're trying to access local files for dev purposes like AJAX or JSON, you can use this flag too.

For Windows go into the command prompt and go into the folder where Chrome.exe is and type

That should disable the same origin policy and allow you to access local files.

Update: For Chrome 22+ you will be presented with an error message that says:

You are using an unsupported command-line flag: --disable-web-security. Stability and security will suffer.

However you can just ignore that message while developing.


14.2k 5 5 gold badges 20 20 silver badges 28 28 bronze badges I had to add a path after --user-data-dir as in --user-data-dir="tmp" for it to work (Chrome 88.0. ) C:\Program Files\Google\Chrome\Application - The default installation path for Chrome on Windows (as of 07/2021). you need to specify 2 path one for chrome.exe and second one for data directory where chrome will store, make data-dir has write permissions "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-site-isolation-trials --disable-web-security --user-data-dir="D:\temp"

For Windows users:

The problem with the solution accepted here, in my opinion is that if you already have Chrome open and try to run the chrome.exe --disable-web-security command it won't work.

Basically, you need to add to the command and run it like this instead (or create a shortcut with it and run a new Chrome instance through that)

which will open a new "insecure" instance of Chrome at the same time as you keep your other "secure" browser instances open and working as normal.

This works by creating a new folder/directory "Chrome dev session" under C: and tells this new Chrome instance to use that folder/directory for its user and session data. Because of this, the new instance is separated from your "normal" Chrome data and your bookmarks and other saved data will not be available in this instance.

Note: only the first "new" instance of Chrome opened with this method, is effected, hence it is only the first tab in the first new Chrome window, which is effected. If you close that instance, you can use the same command again and for example any bookmarks to your local app or similar will still be there as it's pointing to the same folder.

If you want to run multiple "insecure" instances, each one will need its own folder/directory, so you will need to runt he command again with a different folder name. This however also means that each insecure instance will be separated from the others, so any bookmarks or other saves user or session data will not be available across instances.

8,371 6 6 gold badges 26 26 silver badges 37 37 bronze badges This worked for me, but how come this seems not to be documented anywhere?

For Windows:

Open the start menu

Type windows + R or open "Run"

Execute the following command:

For Mac:

Execute the following command:

A new web security disabled chrome browser should open with the following message:

enter image description here

For Mac

If you want to open new instance of web security disabled Chrome browser without closing existing tabs then use below command

It will open new instance of web security disabled Chrome browser as shown below

enter image description here


3,955 1 1 gold badge 13 13 silver badges 17 17 bronze badges

For windows users with Chrome Versions 60.0.3112.78 (the day the solution was tested and worked) and at least until today 19.01.2019 (ver. 71.0.3578.98). You do not need to close any chrome instance.

  1. Create a shortcut on your desktop
  2. Right-click on the shortcut and click Properties
  3. Edit the Target property
  4. Set it to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/ChromeDevSession"
  5. Start chrome and ignore the message that says --disable-web-security is not supported!

BEWARE NOT TO USE THIS PARTICULAR BROWSER INSTANCE FOR BROWSING BECAUSE YOU CAN BE HACKED WITH IT!

5,528 1 1 gold badge 44 44 silver badges 65 65 bronze badges and can you still use chrome debugging on your source code? just tested, you can still use dev tool under this mode. This solution still works as of chrome version 71 Thanks so much!

Using the current latest chrome Version 95.0.4638.69 (Official Build) (64-bit)

windows : click the start button then copy paste the below (change the D:\temp to your liking).:

Linux : start a terminal then run the below command (change the

/tmp directory to your liking)

Note : This solution will start chrome in an isolated sandbox and it will not affect the main chrome profile.

1,395 1 1 gold badge 11 11 silver badges 19 19 bronze badges This is the only solution works for me. I have run this chrome.exe --disable-site-isolation-trials --disable-web-security --user-data-dir="D:\temp" on run window on windows 10. Thanks a lot. Adding --disable-site-isolation-trials really helped me in my case, Chrome v 75.0, Selenium Web Driver, Java. Thanks! This is the only thing that worked in Chrome latest version as of July 2020.

EDIT 2: I can no longer get this to work consistently.

EDIT: I tried using the just the other day for another project and it stopped working. Uninstalling and reinstalling the extension fixed it (to reset the defaults).

Original Answer:

I didn't want to restart Chrome and disable my web security (because I was browsing while developing) and stumbled onto this Chrome extension.

Basically it's a little toggle switch to toggle on and off the Allow-Access-Origin-Control check. Works perfectly for me for what I'm doing.


how I achieve and integrate with my extension as my extension needs to access cross domain. I cannot force user to open the browser wth disable-web-security “the extension no longer exists” can you delete your answer or at least put Edit 3 at the top in bold

Seems none of above solutions are actually working. The --disable-web-security is no longer supported in recent chrome versions.

Not sure why Chrome makes developers life so difficult. It blocks all the possible ways to disable XSS security check even for development use which is totally unnecessary.

[Updated on Jun 23, 2018] Recent I'm developing an SPA app which need to use corsproxy again. But seem none of the corsproxy on the github can meet my requirement.


Кто должен читать данную статью?

На самом деле, все.

Какие запросы используют CORS?

Обзор функциональности

Примеры сценариев управления доступом

Простые запросы

Некоторые запросы не заставляют срабатывать CORS preflight. Они называются “простыми запросами” в данной статье, хотя Fetch спецификация, определяющая CORS, не использует этот термин. Запрос, для которого не срабатывает CORS preflight— так называемый “простой запросы”—это запрос, удовлетворяющий следующим условиям:

  • Допустимые методы для запроса:
  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain
Замечание: WebKit Nightly и Safari Technology Preview устанавливают дополнительные ограничения на значения, допустимые в заголовках Accept , Accept-Language , и Content-Language . Если любой из этих заголовков имеет "нестандартное" значение, WebKit/Safari используют предварительный запрос. Значения, которые WebKit/Safari считают "нестандартными" для этих заголовков, перечислены только в следующих проблемах WebKit: Require preflight for non-standard CORS-safelisted request headers Accept, Accept-Language, and Content-Language, Allow commas in Accept, Accept-Language, and Content-Language request headers for simple CORS, и Switch to a blacklist model for restricted Accept headers in simple CORS requests. Во всех других браузерах подобных дополнительных ограничений нет, потому что они не являются частью спецификации.

Это приведёт к простому обмену запросами между клиентом и сервером, используя CORS заголовки для обработки привилегий:


Посмотрим, что браузер отправит в таком случае на сервер, а также проверим ответ сервера:

Предварительные запросы

В частности, запрос предварительно просматривается, если выполняется любое из следующих условий:

  • Если в запросе используется любой из следующих методов:
  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Ниже приведён пример запроса, который будет предварительно просмотрен.


Замечание: как описано ниже, фактический POST запрос не включает Access-Control-Request-* заголовки; они нужны только для OPTIONS запроса.

Давайте посмотрим на полный обмен между клиентом и сервером. Первый обмен - это предварительный запрос/ответ:

Как только предварительный запрос завершён, отправляется настоящий запрос:

Заголовок Access-Control-Request-Method (en-US) уведомляет сервер как часть предварительного запроса о том, что при отправке фактического запроса он будет отправлен методом запроса POST . Заголовок Access-Control-Request-Headers (en-US) уведомляет сервер о том, что при отправке фактического запроса он будет отправлен с пользовательскими заголовками X-PINGOTHER и Content-Type. Теперь у сервера есть возможность определить, хочет ли он принять запрос в этих обстоятельствах.

Строки 14 - 26 выше - это ответ, который сервер отправляет обратно, указывая, что метод запроса ( POST ) и заголовки запроса ( X-PINGOTHER ) являются приемлемыми. В частности, давайте посмотрим на строки 17-20:

Сервер отвечает с Access-Control-Allow-Methods и сообщает, что POST , GET , и OPTIONS являются жизнеспособными методами для запроса соответствующего ресурса. Обратите внимание, что этот заголовок похож на заголовок ответа Allow (en-US), но используется строго в контексте контроля доступа.

Сервер также отправляет Access-Control-Allow-Headers со значением " X-PINGOTHER, Content-Type ", подтверждая, что это разрешённые заголовки, которые будут использоваться с фактическим запросом. Как и Access-Control-Allow-Methods , Access-Control-Allow-Headers представляет собой список допустимых заголовков через запятую.

Наконец, Access-Control-Max-Age даёт значение в секундах, в течение которого можно кешировать ответ на предварительный запрос без отправки другого предварительного запроса. В этом случае, 86400 секунды - это 24 часа. Обратите внимание, что каждый браузер имеет максимальное внутреннее значение, которое имеет приоритет, когда Access-Control-Max-Age больше.

Предварительные запросы и переадресации

Большинство браузеров в настоящее время не поддерживают следующие переадресации для предварительных запросов. Если переадресация происходит для предварительного запроса, большинство современных браузеров сообщат об ошибке, такой как следующее.

Запрос требует предварительной проверки, которая запрещена для перенаправления между источниками

Протокол CORS изначально требовал такого поведения, но впоследствии был изменён, чтобы больше не требовать его. Однако большинство браузеров ещё не реализовали это изменение и все ещё демонстрируют поведение, которое требовалось изначально.

Поэтому, пока браузеры не догонят спецификацию, вы можете обойти это ограничение, выполнив одно или оба из следующих действий:

  • изменить поведение на стороне сервера, чтобы избежать предварительной проверки и/или избежать переадресации — если у вас есть контроль над сервером, к которому делается запрос
  • изменить запрос так, чтобы это был простой запрос, который не вызывает предварительную проверку

Но если невозможно внести эти изменения, то возможен другой способ:

Однако, если запрос инициирует предварительную проверку из-за наличия в запросе заголовка `Authorization`, вы не сможете обойти ограничение, используя описанные выше шаги. И вы вообще не сможете обойти это, если у вас нет контроля над сервером, на который делается запрос.

Запросы с учётными данными


Вот пример обмена между клиентом и сервером:

Запросы с учётными данными и wildcards

В процессе ответа на запрос с учётными данными сервер обязан указать точный источник в поле заголовка Access-Control-Allow-Origin вместо спецсимвола " * ".

Из-за того что заголовки запроса в примере выше включают заголовок Cookie , запрос провалился бы, если бы значение заголовка Control-Allow-Origin было "*". Но он не провалился: потому что значение заголовка Access-Control-Allow-Origin - " http://foo.example " (действительный источник), а не спецсимвол " * ", контент, удостоверяющий полномочия, возвращается в вызывающий веб-контент.

Отметьте, что заголовок ответа Set-Cookie в примере выше также устанавливает дополнительные куки. В случае неудачи, возникает исключение, в зависимости от используемого API.

Access-Control-Allow-Origin

Возвращаемый ресурс может иметь один заголовок Access-Control-Allow-Origin , синтаксис которого:

Access-Control-Allow-Origin определяет либо один источник, что указывает браузеру разрешить этому источнику доступ к ресурсу; либо — для запросов без учётных данных — значение " * ", которое говорит браузеру разрешить запросы из любых источников.

Если сервер возвращает название хоста, вместо "*", также может быть указан заголовок Vary со значением Origin, чтобы показать клиентам, что ответы с сервера будут отличаться в зависимости от значения заголовка запроса Origin.

Access-Control-Expose-Headers

The Access-Control-Expose-Headers (en-US) header lets a server whitelist headers that browsers are allowed to access. For example:

This allows 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.

The delta-seconds parameter indicates the number of seconds the results can be cached.

Access-Control-Allow-Credentials

The Access-Control-Allow-Credentials (en-US) 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-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.

An example of a preflight request is given above, including an example which sends this header to the browser.

Access-Control-Allow-Headers

Origin

The Origin header indicates the origin of the cross-site access request or preflight request.

The origin is a URI indicating the server from which the request initiated. It does not include any path information, but only the server name.

Note: The origin can be the empty string; this is useful, for example, if the source is a data URL.

Note that in any access control request, the Origin header is always sent.

Access-Control-Request-Method

Examples of this usage can be found above.

Access-Control-Request-Headers

Читайте также: