How to add the "active" field in authentication with AthenticationService? I use CakePHP 4.x

I request help with the following please:
I need to add a field to the authentication system and allow me to validate it with the isValid() function when calling

$result = $this->Authentication->getResult();
if ($result->isValid()) {
....code
}

I have tried the following but it doesn’t work:

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
    {
        
        // Crea una nueva instancia de servicio de autenticación, definiendo la URL donde se debe 
        // redireccionar en caso de que se pretenda entrar a una vista protegida.
        $authenticationService = new AuthenticationService([
            'unauthenticatedRedirect' => '/'.basename(ROOT).'/users/login',
            'queryParam' => 'redirect',
        ]);

        // Carga los campos identificadores (logueo). 
        // Asegúrese de relacionar los campos con los que se valida el logueo
        $authenticationService->loadIdentifier('Authentication.Password', [
            'fields' => [
                            'username' => 'usuario',
                            'password' => 'password',
                        ],
            'where' => [    'estado' => 'Activo'    ],   // This is the other field that i need to validate
        ]);

        // Load the authenticators, you want session first
        $authenticationService->loadAuthenticator('Authentication.Session');

        // Configure form data check to pick email and password
        $authenticationService->loadAuthenticator('Authentication.Form', [
            'fields' => [
                            'username' => 'usuario',
                            'password' => 'password',
                        ],

            'loginUrl' => '/'.basename(ROOT).'/users/login',
        ]);


        return $authenticationService; 
    }

Add a custom finder to your Users table

   // src/Model/Table/UsersTable.php

   public function findActivo(Query $query, array $options): Query
    {
        return $query->where(['active' => true]);
    }

In your getAuthenticationService function in src/Application.php

public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
    {
// ... 
 $authenticationService->loadIdentifier('Authentication.Password', [
    'fields' => [
        'username' => 'usuario',
        'password' => 'passwd',
    ],
    'resolver' => [
        'className' => 'Authentication.Orm',
        'userModel' => 'Users',
        'finder' => 'activo', // default: 'all'
    ],
]);

// ...
2 Likes

@jmcd73 Thank you for your help, it was just what I needed, no more, no less.

Problem solved!