By wim leers on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.2.x
Introduced in version:
8.2.0
Issue links:
Description:
As of Drupal 8.2, it's possible to opt in a particular site to enable CORS for responses served by Drupal.
(This is particularly helpful for fully decoupled Drupal sites which have JS that needs to talk to a Drupal 8 site's REST API. In such cases, that Drupal 8 instance often runs on a separate domain. Due to the same origin policy those requests will be blocked by the browser.)
This is not enabled by default because there are security consequences.
New in default.services.yml:
# Configure Cross-Site HTTP requests (CORS).
# Read https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
# for more information about the topic in general.
# Note: By default the configuration is disabled.
cors.config:
enabled: false
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders: []
# Specify allowed request methods, specify ['*'] to allow all possible ones.
allowedMethods: []
# Configure requests allowed from specific origins.
allowedOrigins: ['*']
# Sets the Access-Control-Expose-Headers header.
exposedHeaders: false
# Sets the Access-Control-Max-Age header.
maxAge: false
# Sets the Access-Control-Allow-Credentials header.
supportsCredentials: false
Note particular that enabled: false key-value pair!
Impacts:
Module developers
Themers
Comments
An example would be nice. I
An example would be nice. I've tried every possible combination I could think of, and CORS requests are still denied.
Contact me to contract me for D7 -> D10/11 migrations.
Yes. I would appreciate if
Yes. I would appreciate if you can provide us with a concrete example for it to be enabled.
This is so far is my config:
but still getting the error below:
XMLHttpRequest cannot load http://localhost:8888/dir/html/oauth/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.Yeah I'm getting the same
Yeah I'm getting the same issue.
Multi domain bug
I forked original module and fixed this bug and pull request. I hope accept this branch.
You can download it in https://github.com/setali/drupal_cors
it works for me.
I'm calling rest services from angular in my localhost.
with Acquia dev desktop for Drupal environment:
in my services.yml file I did this:
Facing same problem for cors
Hi,
I am developing a react app and tried to post requests from react - Axios. But facing the same problem and not able to make the drupal post API work. It is not working for cors issue. Done the required change in services.yml but no result. My change in services.yml file,
still trying to resolve this issue.
https://drive.google.com/open?id=1rPrUdf8Tf5JmKVL1UmkIthzzw2Jy3FjZ
Facing same error
Did you get any solution?
I was able to make a
I was able to make a successful GET request locally using the following cors.config. I transferred these rules over from headers I had previously set in my Apache VHost that I knew were working while experimenting w/ json_api.
(note: this is not an example of a production CORS configuration, just trying to get CORS to work via services.yml file)
Successful POST request to
Successful POST request to
/user/login.allowedHeadersis an array of comma-separated strings, not just a single string.difficulty enabling drupal core cors
Here are my settings in sites/default/default.services.yml:
I'm still having this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403.Is it not activated or something else is the issue?
Yep, getting same error with
Yep, getting same error with same settings.
`Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url]. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). `even though I've specified a domain and all headers and methods.
When this is enabled, shouldn't it write the appropriate rules to docroot/.htaccess? How else can you enable CORS without touching your server config?
You have to copy default
You have to copy default.services.yml to services.yml in order for it to work.
Yes, I've made the edits
Yes, I've made the edits directly to services.yml, not default.services.yml
Found Solution
https://serverfault.com/questions/231766/returning-200-ok-in-apache-on-h...
Have You Tried Clearing the Cache?
I had some issues getting CORS to work after changing the yaml file and adding CORS headers through htaccess. I believe Drupal may have been serving the response from a cache. There's a header in the network response: X-Drupal-Cache was set to HIT.
Have you tried Configuration -> Performance -> Clear All Caches?
My immediate next CORS access attempt worked.
You have to copy default
You have to copy default.services.yml to services.yml in order for it to work.
My Working services.yml
Here is my working services.yml file and corresponding JS request.
Or if you'd rather use promises:
This responds with the appropriate csrf token for the anonymous user.
All the Informations I was missing as a newcommer
Shouldnt be added where the default.services.yaml is ? Like "sites/default/default.services.yaml" .
Then that you should save the changes to the services.yaml.
Maybe you should add a reminder to clear cache.
Everything works as expected now.
Don't forget your web server configuration
Since my team just spent an inordinate amount of time debugging this I thought I'd pass on the knowledge. Enabling this configuration in drupal is not the only step. At least for us we had to configure nginx to give a proper CORS header response in addition to our services.yml file. If you're unable to get it working with just the services.yml change (and a
drush cr) then consider looking at your web server configuration and whether it is also allowing CORS.Thank you
Hey man, I just wanted to thank you for being the one useful comment in this thread. Searching 7 years in the past for answers in this industry should tell you just how desperate I was. I hope you're doing great.
While working on ionic app
While working on ionic app I face the Same issue.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
Made changes to file -> services.yml
enabled: true
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with']
# Specify allowed request methods, specify ['*'] to allow all possible ones.
allowedMethods: ['*']
# Configure requests allowed from specific origins.
allowedOrigins: ['http://localhost:8100']
# Sets the Access-Control-Expose-Headers header.
exposedHeaders: true
# Sets the Access-Control-Max-Age header.
maxAge: 1000
# Sets the Access-Control-Allow-Credentials header.
supportsCredentials: true
*********
Note:- make a copy of default.services.yml and rename to services.yml .
sites/default/services.yml
-> default.services.yml to
-> services.yml
exposedHeaders property is false OR an array of strings
In cors.config, the exposedHeaders property should be an array of header names, or false -- but never 'true' (as some examples on this page are).
See Asm89/Stack/CorsService.php and Read the Access-Control-Expose-Headers docs
I just encountered this today
If you look at line 94 in CorsService.php (Drupal 8.4.4), it's expecting an array and not a Boolean.
$response->headers->set('Access-Control-Expose-Headers', implode(', ', $this->options['exposedHeaders']));Defining 'exposedHeaders' as 'true' rightfully produces an error in the log.
So what's the purpose of this property in services.yml? Should it contain the same header array as the allowedHeaders property?
Once bitten twice shy
Got bitten by this issue again. The following is working for me as of today.
Its disappointing to see that
Its disappointing to see that there are so many development efforts to make Drupal truly headless - Lightening Headless, Contenta, Reservoir etc - yet there all of these efforts are hampered by poorly documented and support CORS, requires editing files, whereas there used to be a module that allowed CORS to be set via a UI.
You must enable CORS in your server!!
Hey everyone,
I enabled CORS in settings.php and it was still not working because I didn't have CORS enabled in my server. Check how to do it, here are the steps for Apache https://enable-cors.org/server_apache.html
Drupal 8.5.X cors problem
I'm trying to access Drupal rest api with Angular 5 but i have a problem in cors :
-----
failed to load http://localhost/drupal/node?_format=json: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
----
i have made changes in default.services.yml and serices.yml but also the same error.
How can i solve thing problem?
The 'Access-Control-Allow-Origin' header contains multiple value
There seems to be a CORS issue with Drupal 8.5.x. I run 8.5.2 with this cors config:
I get:
The 'Access-Control-Allow-Origin' header contains multiple values '*, https://my.domain.com', but only one is allowed. Origin 'https://my.domain.com' is therefore not allowed access.
Insufficient for AMP
This is insufficient when using resources for Accelerated Mobile Pages, see https://www.ampproject.org/docs/fundamentals/amp-cors-requests
This is working for me now with drupal core 8.5.3
This works for me in 8.5.3 and Vue.js
This works for me in 8.5.3. With Vue.js I can view and post content.
Works for me.
I can confirm these settings worked.
Does any actual documentation on this exist?
Where is the
allowedOriginsarray parsed and how? I'm trying to set this up for multiple subdomains that won't be known in advance. Does it accept regular expressions?If you use 'jsonapi' module
If you use 'jsonapi' module and have trouble with: create, update or delete operations then visit

/admin/config/services/jsonapi
and ensure that the following option is selected: "Accept all JSON:API create, read, update, and delete operations."
Does not affect public files
Just a heads up for anyone else, this config has no effect on public files because they are not served through Drupal. They have to be added to the webserver (apache, nginx, etc) config in this case.
All opinions are personal and do not represent anyone but myself.
CORS setting in Drupal 8
I am able to register user by using rest api in drupal,Using React as front end.Below configuration are working for me
cors.config:
enabled: true
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with', 'access-control-allow-origin','x-allowed-header','*']
# Specify allowed request methods, specify ['*'] to allow all possible ones.
allowedMethods: ['*']
# Configure requests allowed from specific origins.
allowedOrigins: ['http://localhost/','http://localhost:3000','http://localhost:3001','http://localhost:3002','*']
# Sets the Access-Control-Expose-Headers header.
exposedHeaders: false
# Sets the Access-Control-Max-Age header.
maxAge: false
# Sets the Access-Control-Allow-Credentials header.
supportsCredentials: true
CORS for specific routes
I am noticing that the old CORS module supported adding CORS to specific paths: https://www.drupal.org/project/cors
Is there a way to enable CORS only for specific paths using services.yml?
I wanted to achieve the same,
I wanted to achieve the same, because I only needed to enable CORS for a specific endpoint, and didn't want it enabled for my entire drupal site due to the security implications. I ended up solving it simply by putting some conditional code in my settings.php:
It's a little bit dirty and old-school, but it's simple and does the trick.
There is another module
There is another module advanced cors which allows detailed configurations for individual paths and there is an issue with an MR available that makes it compatible for Drupal 9 as well.
Full working config Nginx, Ionic/Agular, drupal
Good day,
After spending half a day in this issue I decided to post my working configuration and the logic behind it:
For any post request initiated from the browser, it sends an OPTIONS request to the server to ask if the domain (in my case localhost:8100) has permisions to send information using POST method. As I was trying to login the user my angular service function request looks like this:
As you can see the Content-Type header is sent, so we should allow this header in nginx specifically for the OPTIONS request which seems that isn't done by drupal in the sevices.yml configuration. So jumping into nginx recipe for drupal you should put
This was found in this repository https://github.com/drupal-graphql/drupal-decoupled-app/blob/master/backe...
As you can see when it comes to and OPTION request a 204 code is return so we don't use drupal backend sevices.yml configuration.
In the other hand when other kind of request is sent like POST, GET, PATCH,PUT , the request should be passed to drupal and the services.yml becomes useful
Not sure if there are more options that should be added.
Hope it saves some time.
Julian Mancera
I figured I'd comment here
I figured I'd comment here since I was having trouble testing the CORS response headers with curl commands on the cli or using Postman. The package that Drupal 9 core uses for CORS asm89/stack-cors and the version they are using only adds the CORS headers if there is a `Origin` header on the request (see code). The browser adds that automatically on XHR requests but obviously curl and postman don't. It doesn't look like the latest version of asm89/stack-cors does this check anymore so hopefully it'll be a moot point in the future. Hope this saves someone time, cheers.
Working services.yml for Gatsby and react webform component
We struggled about this too and here is a working
services.ymlexample with minimal configuration to let Gatsby post webform to your backend.Working services.yml for Gatsby and react webform component
We struggled about this too and here is a working
services.ymlexample with minimal configuration to let Gatsby post webform to your backend.I was having issues after a
I was having issues after a Drupal 9 upgrade, finally figured out that things were incorrectly indented, so check that from enabled down to supportsCredentials keys that they are all in the same indentation.
If on Pantheon, Drupal 9....
If you are on Pantheon, Drupal 9.3.x, you also need this patch, https://www.drupal.org/project/drupal/issues/3001809.
I also tried adding the cache_control_override module.
Hopefully that saves someone the days of pain I felt trying to get this to work.
Open everything up
I've been struggling with this for a few days. Finally figured out the following config to open everything up to get dev working:
I had thought it was an issue with my nginx config but after looking at the logs realised it was from the Drupal end. Now I can get some nodes (GET) and update them (PATCH and OPTIONS).
I must say trying to get Drupal up as a backend is far more difficult than using Firebase API mainly due to scattered resources. Wish everything was documented with the JSON-API section - https://www.drupal.org/docs/core-modules-and-themes/core-modules/jsonapi.... Found some help here too but its not completed yet - https://www.drupal.org/docs/develop/decoupled-drupal/getting-started-gui... and https://www.drupal.org/docs/develop/decoupled-drupal/getting-started-gui.... An SDK and/or something like this for Drupal would be use for headless-ness https://firebase.google.com/docs/reference/js/auth#signinwithemailandpas...
CORS Error solution
Working code!
Please follow the steps to help you get worked.
Following are the working services.yml
---
Kind regards,
Thank you,
Rakesh James
Add your client domains list in the server allowedOrigins config
After enabling cors.config in the server service.yml file, ensure allowedOrigns config contains your client application URL's
allowedOrigins: ['http://localhost/','http://localhost:3000','*']
Don't have a trailing slash or duplicates in allowedOrigins
I spent a lot of painful hours before seeing what I did wrong. Somewhere I read that www.somedomain.com and www.somedomain.com/ (with and without trailing slash) are treated as 2 different origins in CORS, and therefore you should add both to your list of origins. That is not correct!
If you do, the origin sent to the browser will have the www.somedomain.com duplicated in the allowed-origins header, which will make it reject your origin (www.somedomain.com). This particularly late in the evening after a long days work is a hard bug to spot in your browsers console and Network tab. The next morning I did spot that the orgin was duplicated, went to my services.yml, removed the one(s) with the trailing slash, and presto it work perfect. Here is my cors bit from my services.yml (domain is changed of course):
cors.config:
enabled: true
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders:
- x-csrf-token
- authorization
- content-type
- accept
- origin
- x-requested-with
# Specify allowed request methods, specify ['*'] to allow all possible ones.
allowedMethods: ["*"]
# Configure requests allowed from specific origins. Do not include trailing
# slashes with URLs.
allowedOrigins:
- https://production.somedomain.de
- https://www.somedomain.de
# Configure requests allowed from origins, matching against regex patterns.
allowedOriginsPatterns: []
# Sets the Access-Control-Expose-Headers header.
exposedHeaders: false
# Sets the Access-Control-Max-Age header.
maxAge: false
# Sets the Access-Control-Allow-Credentials header.
supportsCredentials: true
NB: I have both production and www as sub-domains, because until the new app is ready to launch, I am able to test the production API and app at production.xxxx.de and when the time comes, just point the server for www.xxxx.de to the correct folder.
Pages