Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp auth getuser in beforefilter

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)

like image 991
Omegavirus Avatar asked Mar 26 '26 05:03

Omegavirus


2 Answers

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

like image 66
strohne Avatar answered Mar 28 '26 18:03

strohne


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.

like image 27
ADmad Avatar answered Mar 28 '26 17:03

ADmad