How to manually Authenticate user? Cakephp 4x

User doesn’t stay logged in when I use setIdentity.

    $user = $this->Users->get(1);
    $userInfo = $this->Authentication->getIdentity(); // Returns good.


    $userInfo = $this->Authentication->getIdentity(); // Returns null.

I am not using form. There is no POST happening only dynamically setting user based on some algo…


public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
        $service = new AuthenticationService([
        'unauthenticatedRedirect' => '/login',
        'queryParam' => 'redirect',

        $fields = [
            'username' => 'username',
            'password' => 'password'

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

        // Load the authenticators, you want session first
        $service->loadAuthenticator('Authentication.Session', [
            'identify' => true,

        return $service;

Have you implemented the required interface on your User entitiy class as described here?

Yes. Have implemented that.

Nevermind. I had upgraded the app from 4.0-Beta to 4.1.4. Created a new app and tried the same code. It worked. Guess the upgration didn’t go as planned.