Welcome Guest, Not a member yet? Register   Sign In
Cors policy filter not work
#1
Shocked 
(This post was last modified: 03-15-2024, 02:37 AM by alakian.)

I make a filter to fix CORS Policy errors:

CorsFilter.php:

PHP Code:
namespace App\Filters;

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

class 
CorsFilter implements FilterInterface
{
    public function before(RequestInterface $request$arguments null)
    {

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

    }

    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {
        //
    }


Filters.php
PHP Code:
    public array $aliases = [
        'csrf'          => CSRF::class,
        'toolbar'      => DebugToolbar::class,
        'honeypot'      => Honeypot::class,
        'invalidchars'  => InvalidChars::class,
        'secureheaders' => SecureHeaders::class,
        'cors'          => CorsFilter::class //Add
    ];

    public array $globals = [
        'before' => [
            // 'honeypot',
            // 'csrf',
            // 'invalidchars',
            'cors' //Add
        ],
        'after' => [
            'toolbar',
            // 'honeypot',
            // 'secureheaders',
        ],
    ]; 

Routes.php:
PHP Code:
$routes->post('api/login''Api\Auth\LoginController::jwtLogin', ['filter' => 'cors']); 


Now in action CorsFilter Doesn't work and I've faced with this error:


Code:
Access to XMLHttpRequest at 'http://api/auth/jwt' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Just For Test: I put my code in index.php and surprisingly, this worked truly and fix CORS policy errors.

How to create a filter to fix CORS policy errors?!
Reply
#2

You need to set OPTIONS routes.
If there is no route, control filters does not execute.

Also, you should not send 'Access-Control-Allow-Origin: *'.
You should set your origin URL.
Reply
#3

(03-15-2024, 03:28 AM)kenjis Wrote: You need to set OPTIONS routes.
If there is no route, control filters does not execute.

Also, you should not send 'Access-Control-Allow-Origin: *'.
You should set your origin URL.

I changed routes to:
Code:
$routes->options('api/login', 'Api\Auth\LoginController::jwtLogin', ['filter' => 'cors']);


And Changed:

Code:
header('Access-Control-Allow-Origin: http://localhost:5173');

Both of them return same error.
Reply
#4

Is the route correct? You need to define all routes for OPTIONS requests.

First of all, everyone should understand what CORS is.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Reply
#5

(This post was last modified: 03-18-2024, 12:35 AM by kenjis.)

See CodeIgniter 4 CORS configuration.
Reply
#6
Photo 
(This post was last modified: 08-25-2024, 12:32 AM by rangadurai.)

Code:
<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

/**
* Cross-Origin Resource Sharing (CORS) Configuration
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*/



class Cors extends BaseConfig
{
    /**
    * The default CORS configuration.
    *
    * @var array{
    *      allowedOrigins: list<string>,
    *      allowedOriginsPatterns: list<string>,
    *      supportsCredentials: bool,
    *      allowedHeaders: list<string>,
    *      exposedHeaders: list<string>,
    *      allowedMethods: list<string>,
    *      maxAge: int,
    *  }
    */
    public array $default = [
        /**
        * Origins for the `Access-Control-Allow-Origin` header.
        *
        * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
        *
        * E.g.:
        *  - ['http://localhost:8080']
        *  - ['https://www.example.com']
        */
        'allowedOrigins' => ['http://localhost:3000'],

        /**
        * Origin regex patterns for the `Access-Control-Allow-Origin` header.
        *
        * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
        *
        * NOTE: A pattern specified here is part of a regular expression. It will
        *      be actually `#\A<pattern>\z#`.
        *
        * E.g.:
        *  - ['https://\w+\.example\.com']
        */
        'allowedOriginsPatterns' => ['/^http:\/\/localhost:\d+$/'],

        /**
        * Weather to send the `Access-Control-Allow-Credentials` header.
        *
        * The Access-Control-Allow-Credentials response header tells browsers whether
        * the server allows cross-origin HTTP requests to include credentials.
        *
        * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
        */
        'supportsCredentials' => true,

        /**
        * Set headers to allow.
        *
        * The Access-Control-Allow-Headers response header is used in response to
        * a preflight request which includes the Access-Control-Request-Headers to
        * indicate which HTTP headers can be used during the actual request.
        *
        * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
        */
        'allowedHeaders' => ['Content-Type','Authorization'],

        /**
        * Set headers to expose.
        *
        * The Access-Control-Expose-Headers response header allows a server to
        * indicate which response headers should be made available to scripts running
        * in the browser, in response to a cross-origin request.
        *
        * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
        */
        'exposedHeaders' => ['Content-Type','Authorization'],

        /**
        * Set methods to allow.
        *
        * The Access-Control-Allow-Methods response header specifies one or more
        * methods allowed when accessing a resource in response to a preflight
        * request.
        *
        * E.g.:
        *  - []
        *
        * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
        */
        'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE'],

        /**
        * Set how many seconds the results of a preflight request can be cached.
        *
        * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
        */
        'maxAge' => 7200,
    ];
}



-----+---------------+
| Method  | Route                                        | Name              | Handler                                                            | Before Filters | After Filters |
+---------+----------------------------------------------+--------------------+---------------------------------------------------------------------+----------------+---------------+
| GET    | /                                            | »                  | \App\Controllers\Home::index                                        | cors          | cors          |
| GET    | register                                    | »                  | \CodeIgniter\Shield\Controllers\RegisterController::registerView    | cors          | cors          |
| GET    | login                                        | »                  | \CodeIgniter\Shield\Controllers\LoginController::loginView          | cors          | cors          |
| GET    | login/magic-link                            | magic-link        | \CodeIgniter\Shield\Controllers\MagicLinkController::loginView      | cors          | cors          |
| GET    | login/verify-magic-link                      | verify-magic-link  | \CodeIgniter\Shield\Controllers\MagicLinkController::verify        | cors          | cors          |
| GET    | logout                                      | »                  | \CodeIgniter\Shield\Controllers\LoginController::logoutAction      | cors          | cors          |
| GET    | auth/a/show                                  | auth-action-show  | \CodeIgniter\Shield\Controllers\ActionController::show              | cors          | cors          |
| GET    | api/getprofile                              | »                  | \App\Controllers\Api\AuthController::getProfile                    | cors jwt      | jwt cors      |
| GET    | api/logout                                  | »                  | \App\Controllers\Api\AuthController::logout                        | cors          | cors          |
| GET    | api/isLoggedIn                              | »                  | \App\Controllers\Api\AuthController::isLoggedIn                    | cors 

For me didn't  working cors for api .please help me , what I   did  was wrong?
Reply
#7

Wrong:
PHP Code:
'allowedOriginsPatterns' => ['/^http:\/\/localhost:\d+$/'], 
Try:
PHP Code:
'allowedOriginsPatterns' => ['http:\/\/localhost:\d+'], 

And you should set allowedOrigins or allowedOriginsPatterns, not both.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB