Welcome Guest, Not a member yet? Register   Sign In
Codeigniter CORS bug?
#1

I am creating a Vue 3 project and I am using CodeIgniter 4.3.3 as my API. During the development I've encountered the Cross-Origin Resource Sharing (CORS) issue. So what I did is searched for a solution online what mostly the solution they suggested is to create a filter, so I did and added it on the filter aliases and the before array. Still it doesn't work, Vue 3 is unable to see the headers that I have set in my CorsFilter.php. Now I did some trial and error, what solved the issue is to add the filter that I created in the public/index.php. So my question is why doesn't it work as a filter but works when I add it on the index file? is this a bug? Need help...

app/Filters/CorsFilter.php - does not work
PHP Code:
namespace App\Filters;

use 
CodeIgniter\Filters\FilterInterface;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;

class 
CorsFilter implements FilterInterface
{
    /**
    * Do whatever processing this filter needs to do.
    * By default it should not return anything during
    * normal execution. However, when an abnormal state
    * is found, it should return an instance of
    * CodeIgniter\HTTP\Response. If it does, script
    * execution will end and that Response will be
    * sent back to the client, allowing for error pages,
    * redirects, etc.
    *
    * @param RequestInterface $request
    * @param array|null      $arguments
    *
    * @return mixed
    */
    public function before(RequestInterface $request$arguments null)
    {

        if (array_key_exists('HTTP_ORIGIN'$_SERVER))
        {

            $origin $_SERVER['HTTP_ORIGIN'];

        }
        else if (array_key_exists('HTTP_REFERER'$_SERVER))
        {

            $origin $_SERVER['HTTP_REFERER'];

        }
        else
        {

            $origin $_SERVER['REMOTE_ADDR'];

        }

        $allowed_domains = array(
            'http://localhost:5173/',
            'http://localhost:5173'
        );

        if (in_array($origin$allowed_domains))
        {

            header('Access-Control-Allow-Origin: ' $origin);

        }

        header("Access-Control-Allow-Headers: Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, authorization, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
        header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");

        $method $_SERVER['REQUEST_METHOD'];

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

    }

    /**
    * Allows After filters to inspect and modify the response
    * object as needed. This method does not allow any way
    * to stop execution of other after filters, short of
    * throwing an Exception or Error.
    *
    * @param RequestInterface  $request
    * @param ResponseInterface $response
    * @param array|null        $arguments
    *
    * @return mixed
    */
    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {
        //
    }



app/Config/Filters.php - does not work
PHP Code:
namespace Config;

use 
CodeIgniter\Config\BaseConfig;
use 
CodeIgniter\Filters\CSRF;
use 
CodeIgniter\Filters\DebugToolbar;
use 
CodeIgniter\Filters\Honeypot;
use 
CodeIgniter\Filters\InvalidChars;
use 
CodeIgniter\Filters\SecureHeaders;
use 
App\Filters\JwtFilter;
use 
App\Filters\CorsFilter;

class 
Filters extends BaseConfig
{
    /**
    * Configures aliases for Filter classes to
    * make reading things nicer and simpler.
    */
    public array $aliases = [
        'csrf'          => CSRF::class,
        'toolbar'      => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'jwt'          => JwtFilter::class,
        'cors'          => CorsFilter::class,
    ];

    /**
    * List of filter aliases that are always
    * applied before and after every request.
    */
    public array $globals = [
        'before' => [
            // 'honeypot',
            // 'csrf',
            // 'invalidchars',
            'cors'
        ],
        'after' => [
            'toolbar'
            // 'honeypot',
            // 'secureheaders',
        ],
    ];

    /**
    * List of filter aliases that works on a
    * particular HTTP method (GET, POST, etc.).
    *
    * Example:
    * 'post' => ['foo', 'bar']
    *
    * If you use this, you should disable auto-routing because auto-routing
    * permits any HTTP method to access a controller. Accessing the controller
    * with a method you don’t expect could bypass the filter.
    */
    public array $methods = [];

    /**
    * List of filter aliases that should run on any
    * before or after URI patterns.
    *
    * Example:
    * 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
    */
    public array $filters = [];
    


public/index.php - only this works
PHP Code:
if (array_key_exists('HTTP_ORIGIN'$_SERVER))
{

    $origin $_SERVER['HTTP_ORIGIN'];

}
else if (
array_key_exists('HTTP_REFERER'$_SERVER))
{

    $origin $_SERVER['HTTP_REFERER'];

}
else
{

    $origin $_SERVER['REMOTE_ADDR'];

}

$allowed_domains = array(
    'http://localhost:5173/',
    'http://localhost:5173'
);

if (
in_array($origin$allowed_domains))
{

    header('Access-Control-Allow-Origin: ' $origin);

}

header("Access-Control-Allow-Headers: Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, authorization, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");

$method $_SERVER['REQUEST_METHOD'];

if (
$method == "OPTIONS")
{

    die();

}

// Check PHP version.
$minPhpVersion '7.4'// If you update this, don't forget to update `spark`.
if (version_compare(PHP_VERSION$minPhpVersion'<')) {
    $message sprintf(
        'Your PHP version must be %s or higher to run CodeIgniter. Current version: %s',
        $minPhpVersion,
        PHP_VERSION
    
);

    exit($message);
}

// Path to the front controller (this file)
define('FCPATH'__DIR__ DIRECTORY_SEPARATOR);

// Ensure the current directory is pointing to the front controller's directory
chdir(FCPATH);

/*
 *---------------------------------------------------------------
 * BOOTSTRAP THE APPLICATION
 *---------------------------------------------------------------
 * This process sets up the path constants, loads and registers
 * our autoloader, along with Composer's, loads our constants
 * and fires up an environment-specific bootstrapping.
 */

// Load our paths config file
// This is the line that might need to be changed, depending on your folder structure.
require FCPATH '../app/Config/Paths.php';

// ^^^ Change this line if you move your application folder

$paths = new Config\Paths();

// Location of the framework bootstrap file.
require rtrim($paths->systemDirectory'\\/ ') . DIRECTORY_SEPARATOR 'bootstrap.php';

// Load environment settings from .env files into $_SERVER and $_ENV
require_once SYSTEMPATH 'Config/DotEnv.php';
(new 
CodeIgniter\Config\DotEnv(ROOTPATH))->load();

/*
 * ---------------------------------------------------------------
 * GRAB OUR CODEIGNITER INSTANCE
 * ---------------------------------------------------------------
 *
 * The CodeIgniter class contains the core functionality to make
 * the application run, and does all of the dirty work to get
 * the pieces all working together.
 */

$app Config\Services::codeigniter();
$app->initialize();
$context is_cli() ? 'php-cli' 'web';
$app->setContext($context);

/*
 *---------------------------------------------------------------
 * LAUNCH THE APPLICATION
 *---------------------------------------------------------------
 * Now that everything is setup, it's time to actually fire
 * up the engines and make this app do its thang.
 */

$app->run(); 
Reply
#2

[quote pid="408574" dateline="1681172538"]
same here. header wont work on filter, but if you try to echo something it works
[/quote]
Reply
#3

[quote pid="408574" dateline="1681172538"]
i guess is because filter is  run after body tag?
[/quote]
Reply
#4

Do you have routes with OPTIONS method?
Filter needs a route.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB