2
votes

in my cakephp app with custom auth implementation (see here) i would like to check the auth of a user in the beforefilter method and if he/she is not authenticated i would like to manually render an error page and quit. My problem here is that it seems the auth object gets only filled with data AFTER the action call to an action which require auth. i would need to access auth data in my beforefilter function. how to achieve this? if i try to access it auth->user() it returns NULL, loggedIn() returns always false (because there is no data, makes sense)

4
sorry i confused beforerender with beforefilter - corrected it now - i meant beforefilter - Omegavirus
I use a custom authenticate (ldap) too and in my AppController beforeFilter method i can call $this->Auth->user() without problems and I get my user data. I think that maybe the problem is that your authenticate method in your TokenAuthenticate never returns a user array - arilia

4 Answers

4
votes

I stumbled upon this question and the proposed solution did't work for me.

The proper way to get auth information in beforeFilter in Cakephp 3 is to call

$this->Auth->config('checkAuthIn', 'Controller.initialize');

right after loading the auth component. This is especially useful in stateless authentication scenarios (e.g. token authentication).

You can then get user information in beforeFilter by calling

$user = $this->Auth->user();

See the docs http://book.cakephp.org/3.0/en/controllers/components/authentication.html#deciding-when-to-run-authentication

4
votes

There's no need to check yourself whether a user is authenticated and show error page. Just add a unauthenticated() method to your custom authenticate class like the BasicAuthenticate class does (without setting the headers). The error handler using the exception renderer will generate appropriate error page.

2
votes

from the manual:

class CustomAuthenticate extends BaseAuthenticate {
    public function authenticate(CakeRequest $request, CakeResponse $response) {
        // Return an array of user if they could authenticate the user,
        // return false if not
    }
}

you authenticate method should return an array with the user data. From your link to the other question it seems that it doesn't

0
votes

In CakePHP 2.x this can do the trick

$this->Auth->startup($this);