I'm trying to make a JWT Filter with CI4. But when I set my filter in the app/Config/Filter.php
file, it always throws an error although it is definitely in the app/Filters/
directory.
Class "App\Filters\FilterJwt" not found
I've been trying to create a new directory in the app
path and named it AuthFilter
but in vain.
/Config/Filter.php
:
<?php
namespace Config;
use App\Filters\FilterJwt;
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.
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'authentication' => FilterJwt::class
];
/**
* List of filter aliases that are always
* applied before and after every request.
*/
public array $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'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/*']]
* @var array
*/
public $filters = [
'authentication' => [
'before' => [
'users/*',
'users'
]
]
];
}
/App/Filters/FilterJwt.php
:
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\API\ResponseTrait;
use Exeption;
class MyFilter implements FilterInterface
{
use ResponseTrait;
public function before(RequestInterface $request, $arguments = null)
{
$header = $request->getServer('HTTP_AUTHORIZATION');
try {
helper('jwt');
$encodedToken = getJwt($header);
checkJWT($encodedToken);
return $request;
} catch (Exeption $e) {
return Services::response()->setJson([
'error' => $e->getMessage()
])->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}
Proof that the file is in the directory:
CI4 error:
As you can see, the CI4 framework can't find the "Filters" folder although it's right there.
Rename your class from "MyFilter" to "FilterJwt".
Instead of:❌
/App/Filters/FilterJwt.php
class MyFilter implements FilterInterface
{
//...
Use this:✅
/App/Filters/FilterJwt.php
class FilterJwt implements FilterInterface
{
//...