magento / magento-cloud-docker

All Submissions you make to Magento Inc. (“Magento") through GitHub are subject to the following terms and conditions: (1) You grant Magento a perpetual, worldwide, non-exclusive, no charge, royalty free, irrevocable license under your applicable copyrights and patents to reproduce, prepare derivative works of, display, publically perform, sublicense and distribute any feedback, ideas, code, or other information (“Submission") you submit through GitHub. (2) Your Submission is an original work of authorship and you are the owner or are legally entitled to grant the license stated above. (3) You agree to the Contributor License Agreement found here: https://github.com/magento/magento2/blob/master/CONTRIBUTOR_LICENSE_AGREEMENT.html
Open Software License 3.0
256 stars 192 forks source link

CORS error when integrating with REST API #324

Open tomaszmichalak opened 3 years ago

tomaszmichalak commented 3 years ago

Preconditions

  1. Magento 2.4.2
  2. NGINX image: magento/magento-cloud-docker-nginx:1.19-1.2.2

Steps to reproduce

  1. Setup a sample React App.
  2. Use Magento REST API (integration/admin/token) for authentication.
  3. When calling na API, I get the CORS error.

Expected result

For the NGINX image I am able to define an environment variable:

ENV REST_API_ORIGINS localhost:3000|staging.cloud

and then in the vhost.conf we add required headers:

    # PHP entry point for main application
    location ~ ^/(index|get|static|errors/report|errors/404|errors/503|health_check)\.php$ {
        set $cors_origin "";
        if ($http_origin ~ '^https?://(!ORIGINS!)$') {
            set $cors_origin $http_origin;
        }
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' $cors_origin always;
            add_header 'Access-Control-Allow-Methods' 'POST, GET, OPTIONS' always;
            add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With,X-Cache-Hash' always;
            ### Tell client that this pre-flight info is valid for 20 days
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }
        add_header 'Access-Control-Allow-Origin' $cors_origin always;
       ...
   }

Actual result

Screenshot 2021-06-01 at 21 59 12
shiftedreality commented 3 years ago

Thank you for submitting this issue,

Internal ticket https://jira.corp.magento.com/browse/MCLOUD-7990 was created for processing