Skip to content

Instantly share code, notes, and snippets.

@kenjis
Last active August 9, 2024 04:08
Show Gist options
  • Save kenjis/e757d2b4193b6843724e447e6eaa1254 to your computer and use it in GitHub Desktop.
Save kenjis/e757d2b4193b6843724e447e6eaa1254 to your computer and use it in GitHub Desktop.
CodeIgniter 4 CORS configuration

CodeIgniter 4 CORS Configuration

Important

CodeIgniter 4.5.0 has CORS filter. See https://codeigniter4.github.io/userguide/libraries/cors.html

References

Create CORS filter

app/Filters/Cors.php:

<?php

declare(strict_types=1);

namespace App\Filters;

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

class Cors implements FilterInterface
{
    /**
     * @param array|null $arguments
     *
     * @return RequestInterface|ResponseInterface|string|void
     */
    public function before(RequestInterface $request, $arguments = null)
    {
        /** @var ResponseInterface $response */
        $response = service('response');

        // Set your Origin.
        $response->setHeader('Access-Control-Allow-Origin', 'http://localhost:8081');

        // Set this header if the client sends Cookies.
        // $response->setHeader('Access-Control-Allow-Credentials', 'true');

        if ($request->is('OPTIONS')) {
            $response->setStatusCode(204);

            // Set headers to allow.
            $response->setHeader(
                'Access-Control-Allow-Headers',
                'X-API-KEY, X-Requested-With, Content-Type, Accept, Authorization'
            );

            // Set methods to allow.
            $response->setHeader(
                'Access-Control-Allow-Methods',
                'GET, POST, OPTIONS, PUT, PATCH, DELETE'
            );

            // Set how many seconds the results of a preflight request can be cached.
            $response->setHeader('Access-Control-Max-Age', '3600');

            return $response;
        }
    }

    /**
     * @param array|null $arguments
     *
     * @return ResponseInterface|void
     */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    }
}

Register CORS Filter

app/Config/Filters.php:

<?php

declare(strict_types=1);

namespace Config;

use App\Filters\Cors; // Add this.
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\SecureHeaders;

class Filters extends BaseConfig
{
    /**
     * Configures aliases for Filter classes to
     * make reading things nicer and simpler.
     *
     * @var array<string, class-string|list<class-string>> [filter_name => classname]
     *                                                     or [filter_name => [classname1, classname2, ...]]
     */
    public array $aliases = [
        'csrf'          => CSRF::class,
        'toolbar'       => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'cors'          => Cors::class, // Add this.
    ];
    
    // ...
}

Apply CORS Filter to Routes

app/Config/Routes.php:

$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
    $routes->options('product', '\Dummy');
    $routes->options('product/(:any)', '\Dummy');
    $routes->resource('product');
});

Check Routes and Filters

$ php spark routes

CodeIgniter v4.4.6 Command Line Tool - Server Time: 2024-03-18 06:50:43 UTC+00:00

+---------+-------------------+------+-------------------------------------+----------------+---------------+
| Method  | Route             | Name | Handler                             | Before Filters | After Filters |
+---------+-------------------+------+-------------------------------------+----------------+---------------+
| GET     | /                 | »    | \App\Controllers\Home::index        |                | toolbar       |
| GET     | product           | »    | \App\Controllers\Product::index     | cors           | cors toolbar  |
| GET     | product/new       | »    | \App\Controllers\Product::new       | cors           | cors toolbar  |
| GET     | product/(.*)/edit | »    | \App\Controllers\Product::edit/$1   | cors           | cors toolbar  |
| GET     | product/(.*)      | »    | \App\Controllers\Product::show/$1   | cors           | cors toolbar  |
| POST    | product           | »    | \App\Controllers\Product::create    | cors           | cors toolbar  |
| PATCH   | product/(.*)      | »    | \App\Controllers\Product::update/$1 | cors           | cors toolbar  |
| PUT     | product/(.*)      | »    | \App\Controllers\Product::update/$1 | cors           | cors toolbar  |
| DELETE  | product/(.*)      | »    | \App\Controllers\Product::delete/$1 | cors           | cors toolbar  |
| OPTIONS | product           | »    | \Dummy                              | cors           | cors toolbar  |
| OPTIONS | product/(.*)      | »    | \Dummy                              | cors           | cors toolbar  |
+---------+-------------------+------+-------------------------------------+----------------+---------------+
@kenjis
Copy link
Author

kenjis commented Mar 25, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment