Daniele Dolci
Daniele Dolci

Reputation: 884

CORS Api with symfony

I should make cross domain API with Symfony. There is some bundle for that?

I have tried FOS Rest Bundle but did not seem have solved my problem.

Upvotes: 17

Views: 65265

Answers (5)

Lenny4
Lenny4

Reputation: 1668

Serving static files

Be careful when serving static files as mentionned in NelmioCorsBundle documentation.

Configured at the PHP/application level. This is convenient but it also means that any request serving static files and not going through Symfony will not have the CORS headers added, so if you need to serve CORS for static files you probably should rather configure these headers in your web server

For those of you who are using Api platform and therefore a caddy server.

You can edit your Caddyfile with the header directive to set a default value for Access-Control-Allow-Origin

header ?Access-Control-Allow-Origin "http://localhost:3000"

You can also use env var:

.env

WEB_APP_URL=http://localhost:3000

Caddyfile

header ?Access-Control-Allow-Origin "{$WEB_APP_URL}"

Upvotes: 0

juanitourquiza
juanitourquiza

Reputation: 2194

I used Symfony 5 and Wordpress this code in the file public/index.php works perfectly.

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
    die();
}

Also, I remove package cors .. This Bundle doesn't work for me

Upvotes: 11

WiRight
WiRight

Reputation: 363

I'm not sure that's the right way, but I resolved for me:

  1. Create new event subscriber (like ResponseSubscriber)
  2. Listen KernelEvents::RESPONSE event
  3. In your handler add the following:
if ($event->getRequest()->getMethod() === 'OPTIONS') {
    $event->setResponse(
            new Response('', 204, [
                'Access-Control-Allow-Origin' => '*',
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Headers' => 'DNT, X-User-Token, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type',
                'Access-Control-Max-Age' => 1728000,
                'Content-Type' => 'text/plain charset=UTF-8',
                'Content-Length' => 0
            ])
        );
    return ;
}

Upvotes: 10

Benjamin
Benjamin

Reputation: 31

https://github.com/nelmio/NelmioCorsBundle

or

if you want to write a cors package for yourself, here some tips:

  • the 'to Checked' Origin will be automaticly embedded by any browser in HTTP_ORIGIN
  • do not use a sole '*' wildcard
  • you can cut of the request processing early if u use a request & response listener (if you want)
  • do not only send it with OPTIONS methods (some browser may want it in GET or even POST requests.)

manage your Origin cors list in some config yaml files for example. and validate the HTTP_ORIGIN if it matches your cors list. then send the HTTP_ORIGIN AS "VALID" back.

Access-Control-Allow-Origin: THE_HTTP_ORIGIN_HERE

+ the other Access-Control header. see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more in depth information.


in the end, this mostly the same workflow that https://github.com/nelmio/NelmioCorsBundle uses. my advice: safe your time ;)

TLDR; don't take cors lightly by just use a wildcard, over a bad cors implementation every attacker site can fish a active session from your users.

  • step1: user uses your API, has a session cookie,
  • step2: user visits a random site, which embed code who just requested the browser to trigger a request directly to your api with the cookie credentals.
  • step3: your api must detect this as a attack and not answer with a *.

the victim browser, its not possible to send a forged HTTP_ORIGIN via javascript.

Upvotes: 1

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

I advise you to use NelmioCorsBundle:

https://github.com/nelmio/NelmioCorsBundle

This bundle allows you to send Cross-Origin Resource Sharing headers with ACL-style per-URL configuration.

Is very useful for CORS problem

Upvotes: 22

Related Questions