nelmio / NelmioCorsBundle

Adds CORS (Cross-Origin Resource Sharing) headers support in your Symfony application
https://symfony.com/bundles/NelmioCorsBundle/
MIT License
1.89k stars 108 forks source link

missing CORS header 'Access-Control-Allow-Origin' Front-End REACT, Back-End Symfony 5 with Api Platform and NelmioCorsBundle #176

Closed leotorres9286 closed 2 years ago

leotorres9286 commented 2 years ago

Hi, I'm having problems making requests from a React app to my Api (Api Platform 2.6 - Symfony 5.3 - NelmioCorsBundle 2.2) and some (not all) fail because the api doesn't send the Access-Control-Allow-Origin header. my nelmio_cors.yaml: nelmio_cors: defaults: allow_credentials: false allow_origin: [] allow_headers: [] allow_methods: [] expose_headers: [] max_age: 0 hosts: [] origin_regex: false forced_allow_origin_value: ~ paths: '^/api/': origin_regex: true allow_origin: ['%env(string:CORS_ALLOW_ORIGIN)%'] allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE'] allow_headers: ['Content-Type', 'Authorization'] max_age: 3600 error error2

I'd appreciate it if someone could help me figure out what I'm doing wrong. Why does the same request sometimes fail and sometimes not?

Navds commented 2 years ago

Having same issue

Lehj14 commented 2 years ago

having same issue too

kasteckis commented 2 years ago

Had same issue, currently I just modified public/index.php file to this.

<?php

use App\Kernel;

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");
header("Allow: *");

$method = $_SERVER['REQUEST_METHOD'];

if ($method === "OPTIONS") {
    die();
}

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

return function (array $context) {
    return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
aurorebartel commented 2 years ago

Hi,

I'm not using API Platform but I had the problem with react front end and symfony 6 back end. I create a listener to return custom exception from my symfony API and when error was thrown I had cors allow-origin error. I spent hours looking for a solution (everything in my config seems to be correct) and finally I discovered that creating a subscriber on kernel response fixed the problem (and I just do a $event->getResponse() in the subscriber function).

Really weird but if it can help temporarily

Lubna93 commented 2 years ago

@aurorebartel it works with me too but not sure if it is correct!

Lubna93 commented 2 years ago

For those who are interested, fixed by adding the following EventListener:

App/src/EventListenr/CorsSubscriber

<?php

namespace App\EventListener\HttpKernel;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

class CorsSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::RESPONSE => 'onResponse'
        ];
    }

    public function onResponse(ResponseEvent $event)
    {
        $response = $event->getResponse();
        $response->headers->set('Access-Control-Allow-Origin', '*');
    }

}

And called it in serviece.yaml file:

    app.http_kernel.cors_subscriber:
        class: App\EventListener\HttpKernel\CorsSubscriber
        tags:
            - { name: kernel.event_subscriber }

Then I added the following code to my index.php:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
header("Access-Control-Allow-Methods: *");
header("Allow: *");

$method = $_SERVER['REQUEST_METHOD'];

if ($method === "OPTIONS") {
    die();
}

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

return function (array $context) {
    return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
ErvinSabic commented 2 years ago

Also have this issue. I am on 2.1.

zydrunasG commented 2 years ago

Hey guys, same issue for me, with symfony 4.4.x and nelmio/cors-bundle 2.1.1 Fun fact request still handles correctly and returns response but browser console shows CORS error.

To add header manually via event listeners or while returning request kinda "hackish" solution.

leotorres9286 commented 2 years ago

Sorry, I closed before issuing my comment. I finally understood that when the response from my API returned with an error or with some debug message, the CORS problem occurred. Now I always check my API first so I don't lose my mind with these weird problems. Cheers

Lubna93 commented 2 years ago
/**
* @ApiResource(
* denormalizationContext={
* "disable_type_enforcement"=true
* }
* )
*/

Using this code inside your entity gonna help you to avoid debug messages. Happy for you! :)

M-Agoumi commented 1 year ago

if you are using apache, check if you are enabling headers because they weren't enabled in my server, and no solution worked for me, so try a2enmod headers

peterculak commented 9 months ago

Hi, I'm having problems making requests from a React app to my Api (Api Platform 2.6 - Symfony 5.3 - NelmioCorsBundle 2.2) and some (not all) fail because the api doesn't send the Access-Control-Allow-Origin header. my nelmio_cors.yaml: nelmio_cors: defaults: allow_credentials: false allow_origin: [] allow_headers: [] allow_methods: [] expose_headers: [] max_age: 0 hosts: [] origin_regex: false forced_allow_origin_value: ~ paths: '^/api/': origin_regex: true allow_origin: ['%env(string:CORS_ALLOW_ORIGIN)%'] allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE'] allow_headers: ['Content-Type', 'Authorization'] max_age: 3600 error error2

I'd appreciate it if someone could help me figure out what I'm doing wrong. Why does the same request sometimes fail and sometimes not?

forced_allow_origin_value: '*'

with

forced_allow_origin_value: ~

it doesn't work for me

LBeckX commented 8 months ago

Have the same problem. If I return a

return $this->json(['error' => '400'], Response::HTTP_BAD_REQUEST);

Then i get the response in the browser:

Access to fetch at ''https://my-api-host/my/post' from origin 'https://my-frontend-host' 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.

It seems that in the error response the 'Access-Control-Allow-Origin' header is missing.

I have the following configuration in the NelmioCorsBundle:

nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: [ '%env(CORS_ALLOW_ORIGIN)%' ]
        allow_methods: [ 'GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE' ]
        allow_headers: [ '*' ]
        expose_headers: [ 'Link' ]
        forced_allow_origin_value: ~
        skip_same_as_origin: true
        max_age: 3600
    paths:
        '^/api/':
            allow_origin: [ '*' ]
            allow_headers: [ '*' ]
            allow_methods: [ 'GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE' ]
            forced_allow_origin_value: ~
            max_age: 3600

I use the following packages:

"nelmio/cors-bundle": "^2.3", -> 2.3.1

"symfony/framework-bundle": "6.3.*", -> 6.3.4

Or do you think this is an nginx problem? My NGINX Config is the following in a docker container:


server {
    listen 80 default_server;

    index index.php;
    server_name _;
    server_tokens off;
    root /srv/app/public;

    client_max_body_size 100M;

    location / {
        try_files $uri /index.php$is_args$args;

        if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS, POST, PUT, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,authorization';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
        }
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param APP_CONTEXT api;

        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;

        internal;
    }

    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}
thibaut-lipper commented 4 months ago

Have the same problem. If I return a

return $this->json(['error' => '400'], Response::HTTP_BAD_REQUEST);

[...]

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}

Hi there! I'm having a very similar issue and I was wondering if you had any progress on the matter (as it would be much appreciated ^^)...

vitrus commented 4 months ago

I might help anyone with this (might not be your problem). I got CORS errors on all my POST calls in a symfony application after an update (to PHP 8.2 and Symfony 7.0). All GET requests still worked.

After hours of searching I found an issue in the nginx logs:

12146#12146: *12339 upstream sent too big header while reading response header from upstream

Which I easily solved with these additions in nginx.conf:

    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 32k;

Et voila, CORS issues gone.

joslmt commented 2 weeks ago

@Lubna93 It works doing the cors listeners, thank you, you save my day :)

bienvyManasse123 commented 20 hours ago

same problem but i don't use nginx, just react and symfony 7.1.4, api_platform: 2.6 and nelmio_cors: 2.5 error: Access to XMLHttpRequest at 'http://host/url/url' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. POST http://127.0.0.1:8000/api/users net::ERR_FAILED 200 (OK). Thank's for the help