Restrict access to application backend in CodeIgniter 4

The easiest way to restrict access to application backend, is to check the address of the current page, and if it starts with /admin then check a logged user rights. This can be implemented through filters, that appeared in the fourth version of the framework.

  1. Add a Basic App Core library contains an admin filter via Composer.
composer require "basic-app/core:dev-master
  1. Set up a new filter in filters config: /Config/Filters.php.
public $aliases = [
    ...
    'admin' => \BasicApp\AdminFilter::class
];
...
public $filters = [
    ...
    'admin' => [
        'before' => ['admin', 'admin/*']
    ]
];

If you have an another implementation of users and rights, then you can inherit your class from BasicApp\BaseAdminFilter and override currentUserId(), checkAccess() and getUser() methods.