CodeIgniter Forums
Best practice/how to deal with CORS - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Best practice/how to deal with CORS (/showthread.php?tid=90637)



Best practice/how to deal with CORS - Willen - 04-12-2024

Hello! 

I have had a project that have been running Codeigniter 3 for a long time and now I'm on a journey to convert it to Codeigniter 4.

I have a separate front end and I'm using Codeigniter as an api. When I tested my endpoints in postman it was working fine, then when I tested it in browser I was getting multiple CORS-erros, like:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I read a bunch of threads on this forum and found one solution in this thread: https://forum.codeigniter.com/showthread.php?tid=80043 . The solution was to make a CORS-Filter and add options-routes for all my endpoints: https://gist.github.com/kenjis/e757d2b4193b6843724e447e6eaa1254

Cors-filter:

Code:
<?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', getenv('CORS_ORIGIN'));

        // 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)
    {
    }
}


Is this the best practice in dealing with cors preflights? Without the options route defined, I get CORS errors. Do I have to add options for all of my endpoints or am I missing something?

Code:
$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
  $routes->options('/auth/login', 'Auth::login');
  $routes->post('/auth/login', 'Auth::login');



RE: Best practice/how to deal with CORS - kenjis - 04-13-2024

See https://codeigniter4.github.io/CodeIgniter4/libraries/cors.html