Authentication and session data

I use this plugin for login: Quick Start - 2.x

After logging in, all the fields in the users table are written to the session Auth.
Can only a user ID be entered in a session Auth? I don’t want all the fields in a session.

Thank You

Why does it matter what fields are there?

You have to extend the FormAuthenticator (or another Authenticator that you use)

And instead of returning the full user

return new Result($user, Result::SUCCESS);

you can return an array with the only data you’ll use

return new Result(['id' => $user->id], Result::SUCCESS);

I prefer that way, and on each request retrieve the user from the database. It allows fresh changes in case another user changes your logged-in user. (Like deactivate your user)

1 Like

If the user has a lot of columns, then it does not take up space in the session. At the same time, there is no sensitive data in the session.

Thanks! So do I have to create a new script, this way?

/src/Authenticator/FormAuthenticator.php

Would this be an example of what a script should look like?

Yes and when configuring the service in the Application class, change to this

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
    // ......
    $service->loadAuthenticator('App.Form', [ // App instead of Authentication
        // .... your config
    ]);
    // ....
}

Another option would be set the finder option of the resolver to only retrieve the id column in the finder. But i didn’t test it yet.

1 Like

But storage space is so cheap, and the session contents only ever live on the server, so who cares if it has sensitive information in it?

I thought that the saved session could be misused by someone.

The solution through your own resolver is here and it works - thank you for the advice.

src/Application.php

/**
 * Returns a service provider instance.
 *
 * @param \Psr\Http\Message\ServerRequestInterface $request Request
 * @return \Authentication\AuthenticationServiceInterface
 */
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
    // ......
        $service->loadIdentifier('Authentication.Password', [
            'fields' => $fields,
            'resolver' => [
                'className' => 'Authentication.Orm',
                'finder' => 'userAuthenticator',
            ],
        ]);
    // ....
}

src/Model/Table/UsersTable.php

    /**
     * Custom finder - findUserAuthenticator
     *
     * @param \Cake\ORM\Query $query The query to DB
     * @return \Cake\ORM\Query
     */
    public function findUserAuthenticator(Query $query)
    {
        return $query->find('all', [
            'fields' => [
                'id',
                'email',
                'password',
                'logged',
            ],
        ]);
    }