Issues with connexion and UsersController and form

Hello, I have some questions about authentication with cake.

  • First, I can’t find how to configure the fact that I stay connected for 1 hour, 1 day, 1 week or 1 month. The basic connection duration seems quite short.

  • also, even when my credentials are good, I often have this error (see screenshot) coming up. I understand that it’s form protection but it seems quite random and after trying several times, I managed to connect.

  • I am looking for a way to add double authentication by email or by an app? do you have any leads?

Thank you !

  1. Depends on what kind of (persistent) authenticator you are using. Typically CakePHP Authentication uses the CookieAuthenticator. Therefore setting the expire time for your cookies will define how long a users keeps being logged in since the cookie is sent with every request.

  2. The FormProtection Component can lead to problems if you adjust your Forms via JS (intentionally or unintenationally via e.g. a rogue Browser Extension). I usually leave it disabled if its not a public form which can be submitted by unauthenticated users.

  3. GitHub - CakeDC/auth: Auth objects for CakePHP has e.g. 2FA via Google Authenticator. You can look at its implementation in a custom AuthenticationService in auth/AuthenticationService.php at 6.next-cake4 · CakeDC/auth · GitHub

I followed the CookBook tutorial. How can I decide the duration of the cookie? I’m not even sure it’s there because I don’t see it in the dev tool.

It’s my login form so I think the form protection is useful right? I don’t have an extension except ADBlock so I don’t see what could be blocking?

My code if it can help ?

APPLICATION.PHP

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

        // Define where users should be redirected to when they are not authenticated
        $service->setConfig([
            'unauthenticatedRedirect' => Router::url([
                    'prefix' => false,
                    'plugin' => null,
                    'controller' => 'Archives',
                    'action' => 'index',
            ]),
            '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' => Router::url([
                'prefix' => false,
                'plugin' => null,
                'controller' => 'Users',
                'action' => 'login',
            ]),
        ]);
      

        $service->loadAuthenticator('Authentication.Cookie', [
            'fields' => $fields,
            'loginUrl' => '/users/login',
        ]);


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

USERS CONTROLLER

public function login()
	{
		$this->viewBuilder()->setLayout('login');
		$result = $this->Authentication->getResult();

		if ($result->isValid()) {
			$this->Flash->success(__("Succès : Vous êtes connecté."));
			$this->redirect(['controller' => 'Archives', 'action' => 'index']);
		}
		if ($this->request->is('post') && !$result->isValid()) {
			$this->Flash->error('Erreur : Identifiants incorrects.');
		}
	}

LOGIN VIEW

<div class="mt-3">
<?php echo $this->Form->create();?>
    <div class="form-floating">    
    <?php
        echo $this->Form->control('email',[
            'class'=>'form-control',
            'id'=>'floatingInput',
            'placeholder'=>"Adresse email",
            'label'=>false,
        ]);
    ?>
    </div>
    <div class="form-floating">
<?php
    echo $this->Form->control('password',[
        'class'=>'form-control',
        'placeholder'=>"Mot de passe",
        'label'=>false,
    ]);
?>
</div>

<div class="checkbox mb-3">
   <?= $this->Form->control('remember_me', ['type' => 'checkbox']); ?>
</div>

<?php
    echo $this->Form->button("Connexion",[
        'class'=>'w-100 btn btn-lg btn-primary',
    ]);
    echo $this->Form->end();
?>

</div>

The screen error I have sometime when I try to login (with good credentials)

Regarding the Cookie settings: See Authenticators - 2.x

So you could do

$service->loadAuthenticator('Authentication.Cookie', [
    'fields' => $fields,
    'loginUrl' => '/users/login',
    'cookie' => [
        'expires' => new DateTime('+1 month'),
    ]
]);

We don’t mention everything in the Authentication Tutorial because otherwise it would be huuuuuuge.

Regarding the FormProtection Error: Please enable debug mode so you get a more telling error of what exactly failed in your FormProtection processing.

Hello, thank you very much for your feedback. Indeed, it looks good for the cookie.

For the form error, I put the screenshot with the debug to true. Do you need more info to help me?

For those who come across this topic and are looking for 2-factor authentication with CakePHP 4, you can look here:

GitHub - CakeDC/users: Users Plugin for CakePHP also has preconfigured OTP/2FA as well as you can see here: