Keval Domadia
Keval Domadia

Reputation: 4763

How to manually (formless) Authenticate user? Cakephp 4x

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

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

Somewhere:

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

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

Application.php

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');

        return $service;
    }

Upvotes: 0

Views: 203

Answers (1)

Oerd
Oerd

Reputation: 2313

You are setting the principal information on the Authentication but you loose it on the next request because it's not persisted (I'm sparing you the "http is stateless" song...)

Part of your setIdentity should also be persisting the identity. This can be achieved in different ways:

  • in the session, when using sessions
  • in a JWT token, when using tokens

Here is how AuthenticationService does it in persistIdentity. I suggest you also have a look at the JWT auth configuration.

Upvotes: 1

Related Questions