In CakePHP - prior to version 4.x - it had a simple Auth
component which dealt with setting up authentication/authorization and made it very easy to do things like get a logged-in user ID with one line of code.
In 4.x the Auth
component has been dropped and split out into separate Authentication and Authorization components.
There seems to be a lack of information about how you use these two new components (the docs are very sparse and the README's on GitHub provide little of use).
What I've managed to do so far is:
Followed the CMS Tutorial to set up a CakePHP 4.3.7 app with both Authentication and Authroization.
In a Controller method I added the following. I was only able to find this because somebody had posted an updated answer on Cakephp - get user id in controller when using Auth - it doesn't actually seem to be documented anywhere:
$identity = $this->request->getAttribute('authentication')->getIdentity();
debug($identity);
This gives:
object(Authentication\Identity) id:0 {
'config' => [ ]
'data' => object(App\Model\Entity\User) id:1 {
'id' => (int) 7
'first_name' => 'Andy'
'last_name' => 'My Last Name'
'email' => 'andy@example.com'
If I do debug($identity->data->id);
I'd expect to be able to read the id
property of the object and have it return my user ID, 7 in this case. It gives null
.
I can't help but think this is the wrong way to do it and there should be an easy method to just return the logged in user ID given this is almost always going to be required in any use-case.
Please can somebody either point to where this is in the docs, or advise how it can be achieved?