Check login on all pages

Hi, I have a question. I set up a separate admin area for my app. It is on separate URL, so completely new code project. All works fine for now, but….

I would like to check access to all pages except the login and logout pages. For this, we have defined an exception in my AppController.

    public function beforeFilter(\Cake\Event\EventInterface $event): void
    {
        parent::beforeFilter($event);
        // for all controllers in our application, make index and view
        // actions public, skipping the authentication check
        $this->Authentication->addUnauthenticatedActions(['login', 'logout']);
    }

In my user/index methode I tried something like

$identity = $this->Authentication->getIdentity();
        //dd($identity);
        if($identity == null)
        {
            //dd("not logged in");
            $this->Flash->error(__('You are not logged in'));
            return $this->redirect(['action' => 'login']);
            
        }

But when I try to call the url directly http://localhost/myproject/users/ then I will get an error:

The request to `/users/` did not apply any authorization checks.

But what I expect to get in the login page with an error that you are not logged in.

Is there some possibility to get the access checked on a higher level and not in each methode. And maybe with an option to get the exception caught and show a nice error message.

Thanks

Authentication is not the same as Authorization.

If you don’t call

$this->Authorization->authorize($article);

to actively check for authorization, you need to call

$this->Authorization->skipAuthorization();

to tell cakephp, that it doesn’t need to check it.