CakePHP 4. Plugin authentication. An array in session, not an object

Hi guys.

I am using cakephp (version 4.1.4) and trying to do authentication with cakephp/authentication plugin (version 2.3.0). Based on the documentation, everything worked out for me, only I expected to see an array in the session, and not an App\Model\Entity\User object.

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
    {
        $service = new AuthenticationService();

        // Define where users should be redirected to when they are not authenticated
        $service->setConfig([
            'unauthenticatedRedirect' => '/users/login',
            'queryParam' => 'redirect',
        ]);

        $fields = [
            IdentifierInterface::CREDENTIAL_USERNAME => 'email',
            IdentifierInterface::CREDENTIAL_PASSWORD => 'password'
        ];
        // Load the authenticators. Session should be first.
        $service->loadAuthenticator('Authentication.Session');
        $service->loadAuthenticator('Authentication.Form', [
            'fields' => $fields,
            'loginUrl' => '/users/login'
        ]);

        // Load identifiers
        $service->loadIdentifier('Authentication.Password', compact('fields'));

        return $service;
    }

Is there a way to write an array and not an object to the session?
Thank.

This is the proper behavior for Authentication and you won’t want to change it (cascading failures of all dependent systems).

But you can write any additional data you want to the session. Or write a getter to retrieve the object and convert it into any form you want. Or add methods to the User Entity to return it’s values in any pattern you want.

I’m curious though. Why can’t you work from the object?

I wanted to use (without additional edits) the dereuromark/cakephp-tinyauth plugin, but it assumes storing an array in a session.

I have a CakePHP 3.2 application where the authentication data is stored in the session as an array.

My impression is that this plugin replaces the other one you’re using. I could be wrong…