Welcome Guest, Not a member yet? Register   Sign In
How do I 'properly' protect a controller?


Maybe I'm not getting it. But if I try to 'protect' an – let's say – adminController using filters, I seem to face a 'hole' in applying them.

If I have:


$routes->get('/', 'Admin::index'); // This is the default route pointing to the admin controller
$routes->add('admin', 'Admin::index', ['filter' => 'admin-auth']);

Now, it seems kind of 'odd' that I HAVE to protect the controller through setting a filter in the route ... what if I 'forget' to do so (as illustrated in the case above for the '/' route)? Then I'm vulnerable …

Back in the old days (CI3), I would create an AdminController, implement authorization in the constructor and extend that. I know I can do this  today in CI4 as well (apart from this parent::initController thing which 'act's like a constructor confusing the crap out of me – why not simply use __construct?), BUT why is it that we're 'supposed' to use filters for that exact case (according to the docs), as I see it as not being as 'bullet proof' using filters vs implementing it directly in the controller.

Maybe someone can shed some light on the decisions behind this 'approach' ... or maybe share some 'clever' way of achieving this in the best and most portable (reusable) way possible?

(This post was last modified: 09-24-2020, 08:28 AM by captain-sensible.)

A controller is called by a route; so really its about (in my thinking protecting your route) lets say i have a url segment after domain /removeBlog which is defined in a route :


Using a filter and code i can first before going using Class and method (Blog::delBlogForm)
do some checking via a filter.

I have a class called " MyFilter3.php" (located in apache at /var/www/htdocs/CI4.0.4/app/Filters/) which has :

public function before(RequestInterface $request, $arguments = null)
           $logic=isset($_SESSION['role']) ;
            return redirect('spam');

how this works is that if admin is not logged in and therefore a SESSION variable is not set/null etc
then what happens is that for the url : http://mydomain.com/removeBlog they will (if not logged in) simply be brushed off to a custom page "does not exist "

Note you have to declare your filters in app/Config/Filters.php as example :

public $filters = [
    'myfilter3' => ['before' => ['removeBlog']],

if admin "IS Loggedin " and goes to url /removeBlog then they will see loaded a "view" which has a form where arguments such as blogId can be entered. The form gets submitted via "POST" to another Blog Class method to process. I have similar filter protection on that as well !

Theme © iAndrew 2016 - Forum software by © MyBB