Create CI4 Filters (middleware) to authenticate, throttle, or transform requests before controllers.
Filters in CI4
// app/Filters/AuthFilter.php
namespace AppFilters;
use CodeIgniterFiltersFilterInterface;
class AuthFilter implements FilterInterface {
public function before(RequestInterface $request, $arguments = null) {
if (!session()->get("logged_in")) {
return redirect()->to("/login");
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {
// post-processing
}
}
// Register in app/Config/Filters.php
public array $aliases = [
"auth" => AppFiltersAuthFilter::class,
"admin" => AppFiltersAdminFilter::class,
];
// Apply to routes
$routes->group("admin", ["filter" => "auth:admin"], function($r) {
$r->get("/", "AdminDashboard::index");
});
// Apply globally
public array $globals = [
"before" => ["honeypot", "csrf"],
"after" => ["secureheaders"],
];