About Lesson
In CodeIgniter 4, authentication filters are a way to perform actions before and after the execution of controller methods. Below is an example of how you can create a simple authentication filter in CodeIgniter 4.
1. First, create a new file for your filter. Let’s name it AuthFilter.php
. Place it in the app/Filters
directory.
<?php namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class AuthFilter implements FilterInterface {
public function before(RequestInterface $request, $arguments = null)
{
$path = $request->uri->getPath();
if(!session()->get('login_status')) {
return redirect()->to(base_url("login"));
}
}
//--------------------------------------------------------------------
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}
2. Next, you need to register your filter in the app/Config/Filters.php
file.
<?php
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;
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,
'auth' => \App\Filters\AuthFilter::class,
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array<string, array<string, array<string, string>>>|array<string, list<string>>
*/
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/*']]
*/
public array $filters = [];
}
3. Replace'your/protected/route'
with the actual route or routes you want to protect with your authentication filter.
// My Account Routes
$routes->group('myaccount', function($routes) {
$routes->get('/', 'myaccount\MyAccount::index', ['filter' => 'auth']);
$routes->post('update', 'myaccount\MyAccount::update', ['filter' => 'auth']);
});