Kors отключить в браузере firefox
Is there any way to disable the Same-origin policy on Google's Chrome browser?
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
34 Answers 34
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:
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.)
for Chrome Version 96 , Use "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --disable-features=IsolateOrigins,site-per-process --user-data-dir="C://ChromeDev" . just add --disable-features=IsolateOrigins,site-per-process , See this
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.
If you would like your existing user directory, on MacOS you may find it under: --user-data-dir="/Users/
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.
I don't know but maybe it's because in general, Google/Chrome probably don't want you to disable the security.
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:
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
Using the current latest chrome Version 100.0.4896.127 (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.
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!
It works for me on Linux, but with a little modification google-chrome --disable-site-isolation-trials --disable-web-security --user-data-dir="/tmp"
I have version 95, but adding --disable-site-isolation-trials does not work. Any workaround for this?
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.
- Create a shortcut on your desktop
- Right-click on the shortcut and click Properties
- Edit the Target property
- Set it to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/ChromeDevSession"
- 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!
Worked like a charm. I can't believe Chrome doesn't allow developers to disable this without starting a new session. At least they have a way though.
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
This extension won't work for local files, unfortunately. Stick to the --disable-web-security switch in that case.
@bryc It's not really meant to. Consider though that you can use --allow-file-access-from-files instead of disabling all 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.
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.
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).
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.
i think that setting "network.http.referer.XOriginPolicy" to 1 worked for me (Firefox beta). I am unsure how bad (insecure) it is to leave it like this.
firefox didn't allow an option for engineers to disable CORS for development, but life, uh, finds a way
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!
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
This answer fixed the font-awesome download failed issue I was having on my local dev environment from a cross-origin restriction.
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.
This attempt has been posted several times here and is told on other sites too, but it doesn't have any effect. I read the Mozilla guide to same-origin policies:
but it just explains CORS and the related topics. A workaround to enable it on Firefox is not listed.
Is there a definitive solution?
PS: FORCECORS does not work either somehow.
5 Answers 5
Do nothing to the browser. CORS is supported by default on all modern browsers (and since Firefox 3.5).
security.fileuri.strict_origin_policy is used to give JS in local HTML documents access to your entire hard disk. Don't set it to false as it makes you vulnerable to attacks from downloaded HTML documents (including email attachments).
It's only possible when the server sends this header: Access-Control-Allow-Origin: *
If this is your code then you can set up it like this (PHP):
just a warning note, adding Access-Control-Allow-Origin: * everywhere enables CORS for anyone and everyone. While you should have security measures in place whatever the case, if the API is only used by specific resources then you should limit which domains are allowed via a comma-separated-list instead of supplying *
This Firefox add-on may work for you:
It can toggle CORS on and off for development purposes.
I was stucked with this problem for a long time (CORS does not work in FF, but works in Chrome and others). No advice could help. Finally, i found that my local dev subdomain (like sub.example.dev) was not explicitly mentioned in /etc/hosts, thus FF just is not able to find it and shows confusing error message 'Aborted. ' in dev tools panel.
Putting the exact subdomain into my local /etc/hosts fixed the problem. /etc/hosts is just a plain-text file in unix systems, so you can open it under the root user and put your subdomain in front of '127.0.0.1' ip address.
The JavaScript code is doing this:
In my case this solved the restriction/situation just perfectly. There isn't any need to hack Firefox or servers. Just load your JavaScript/HTML file with that small PHP file into the server and you're done.
Многие проблемы быстрее решаются поиском по форуму и чтением FAQ, чем созданием новой темы и томительным ожиданием ответа.
№1 23-10-2012 12:10:09
Отключить запрет на кроссдоменные запросы
№2 24-10-2012 08:08:20
Нашел плагин. И все же интересно - есть ли у Firefox внутренние настройки, которые могут отключить эту раздражающую опеку без спроса за нашу безопасность?
№3 24-10-2012 09:23:44
Это вас она раздражает ввиду вашей специфики. У 99% пользователей такой специфики нет, и отключение политики same-origin-policy будет чревато большой свободой творчества для трояно- и вирусописателей. Если именно вам очень надо - используйте CORS.
№4 24-10-2012 22:22:23
А что за плагин?
***
Это вас она раздражает ввиду вашей специфики.
У меня тоже такая специфика.Ещё знаю несколько человек с такой темой.
А уж любители Greasemonkey наверно все хотят отключить этот запрет.
Нас больше чем 1%
№5 24-10-2012 23:33:33
hydrolizer
CORS ничем не лучше same origin, т.к. сайт должен отдавать в заголовках Access-Control-Allow-Origin:, а этого никто не делает, если конечно это не мой сайт.
questman
"Force CORS" называется.
Теперь мне не надо писать ни аналогичный плагин самому, ни скрипт для прокси-сервера, который плевал бы на все эти надуманные ограничения и вставлял бы Access-Control-Allow-Origin во все заголовки.
Смешное ограничение, которое никак не остановит злоумышленников, но очень и очень мешает всем JavaScript-программистам.
№6 24-10-2012 23:36:32
Прошлое – это локомотив, который тянет за собой будущее. Бывает, что это прошлое вдобавок чужое. Ты едешь спиной вперед и видишь только то, что уже исчезло. А чтобы сойти с поезда, нужен билет. Ты держишь его в руках. Но кому ты его предъявишь?
Виктор Пелевин. Желтая стрела
№7 25-10-2012 03:59:44
Force CORS" называется
и вставлял бы Access-Control-Allow-Origin во все заголовки
Догадайтесь с трех раз, что делает упомянутое вами расширение. Совет использовать CORS именно к этому и относился.
№8 25-10-2012 20:04:41
Это понятно.
Меня больше всего интересует iframe
А точнее его содержимое.
Есть сайт на нём есть iframe,внутри другой сайт.
Как сделать так чтобы получить доступ к этому другому сайту к его элементам?
Потому что даже кастом батонс кнопка "переводчик" не работает если нужный текст находится в iframe.
Тоже самое и со скриптами для Greasemonkey
№9 25-10-2012 21:14:35
Потому что даже кастом батонс кнопка "переводчик" не работает если нужный текст находится в iframe.
Это почти наверняка проблема данной конкретной кнопки – в ней что-то делается не так.
Добавлено 25-10-2012 21:19:08
Есть сайт на нём есть iframe,внутри другой сайт.
Как сделать так чтобы получить доступ к этому другому сайту к его элементам?
Отредактировано Infocatcher (25-10-2012 21:19:08)
Прошлое – это локомотив, который тянет за собой будущее. Бывает, что это прошлое вдобавок чужое. Ты едешь спиной вперед и видишь только то, что уже исчезло. А чтобы сойти с поезда, нужен билет. Ты держишь его в руках. Но кому ты его предъявишь?
Виктор Пелевин. Желтая стрела
№10 25-10-2012 21:47:45
Infocatcher
А теперь представим, что зловредный сайт открывает фрейм со станицей банка.
Тем не менее, существует аналогичная уязвимость, о которой я не буду говорить, но которую никто не может закрыть. И ни same origin, ни CORS здесь не помогут. Кажется, я вижу намеки на то, что введут ограничения аналогичные им, но это убъет Веб, как мы его знаем и привыкли. Так что это аналогично запрету гражданам выходить на улицу под предлогом борьбы с уличными преступлениями. Вместо того, чтобы продумать и улучшить защиту, ухудшают функциональность веб-браузеров.
hydrolizer
Я знаю как работает этот плагин - в его описании все есть, даже не надо внутрь кода лезть. А CORS - это запрет (или разрешение - смотря как смотреть на стакан) на междоменные запросы, если они не содержат определенного разрешающего заголовка, а не метод преодоления этих ограничений.
questman
Можно попробовать с помощью GM_xmlhttpRequest() или ForceCORS загружать содержимое iframe-ов своим JavaScript, а затем заменять имеющиеся iframe на свои, вставляя в них скачанный HTML код. Главное (междоменный запрос) преодолевается с помошью плагинов, а затем остается только создать свои фреймы и наполнить их аналогичным содержанием, а "запретные" оригинальные iframes удалить.
Кто должен читать данную статью?
На самом деле, все.
Какие запросы используют 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 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
Читайте также: