0

After a good amount of time, I found the solution through an authentication plugin that is easy to install via composer with the command:

composer require "cakephp/authentication:^2.0"

After that, just generate the crud via terminal and check them to send json type data. It can be done as follows:

$this->response
    ->withType('application/json')
    ->withStatus(200)
    ->withStringBody(json_encode($dataOrMessage));

Add the function in entity to encrypt the password that the user registers:

protected function _setPassword(string $password) : ?string {
    if (strlen($password) > 0) {
        return (new DefaultPasswordHasher())->hash($password);
    }
}

Implementing the AuthenticationServiceProviderInterface interface in the Application class and adding its requirements, in addition to the login and logout functions of the aforementioned plugin, you can view here

The login function will look something like this:

public function login() {
    if ($this->request->is('post')) {
        $result = $this->Authentication->getResult();

        if ($result && $result->isValid()) {
            return $this->response
                ->withType('application/json')
                ->withStatus(200)
                ->withStringBody(json_encode($result->getData()));
        } else {
            return $this->response
                ->withType('application/json')
                ->withStatus(401)
                ->withStringBody(json_encode(['message' => 'User or password incorrect!']));
        }
    }
}

There is not only this solution, but it was the one I found and that I found to be easier to implement.

  • 1
    Would you please check this example to hash your password and then try again ? https://book.cakephp.org/4/en/tutorials-and-examples/cms/authentication.html#adding-password-hashing – Alimon Karim Jan 15 '23 at 09:42
  • I tried again with the link sent, but still no success. I add the function to encrypt the password in the users entity. – Yuri Aguiar Jan 16 '23 at 18:01

0 Answers0