flightphp / core

An extensible micro-framework for PHP
https://docs.flightphp.com
MIT License
2.63k stars 407 forks source link

Cors in Framework #486

Closed jalbertnunezf closed 9 months ago

jalbertnunezf commented 1 year ago

Any solution to the cors in the framework??, I put the headers after the require vendor but still no result

`require 'vendor/autoload.php';

header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE'); header('Access-Control-Allow-Headers: Content-Type');`

ReimuHakurei commented 1 year ago

I just tested this to double-check, and this works perfectly fine for me.

Are you sure you do not have some other error in your code which is breaking headers, such as a random byte or two of output before you try to send the headers? (ie: UTF-8 BOM, random linebreak in another file you are including, etc)

kuopassa commented 1 year ago

Send headers before output. ;-)

pierresh commented 1 year ago

Hello,

Just a remark, that is not very good to bypass Cors with header('Access-Control-Allow-Origin: *'); It works but if your customer do a penetration test, it would be raised as a security issue.

I do that way:

I have a class to define with the Cors, filtering if the origin is allowed or not. Our app is developed with Angular and Ionic, so I whitelist related URLs.

namespace Shared;

class Cors
{
    public static function set(): void
    {
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            self::allowOrigins();
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');
        }

        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                header(
                    'Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS'
                );
            }
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                header(
                    "Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"
                );
            }
            exit(0);
        }
    }

    private static function allowOrigins(): void
    {
        $allowed = [
            'capacitor://localhost',
            'ionic://localhost',
            'http://localhost',
            'http://localhost:4200',
            'http://localhost:8080',
            'http://localhost:8100',
        ];

        if (in_array($_SERVER['HTTP_ORIGIN'], $allowed)) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        }
    }
}

then I could define the cors

require './vendor/autoload.php';

use Shared;

Cors::set();
krmu commented 9 months ago

@n0nag0n also done.

n0nag0n commented 9 months ago

Thanks @krmu