Authentication: Auth Component (Basic)

CakePHP 4 Authentication Using Auth Component (Basic)

This tutorial will show how to use the Auth component to create an authentication in CakePHP. Download the CakePHP (refer here) and create your database with the users table. The compulsory field for this tutorial is id, username, password, email, created and modified. Bake the users table and you are ready for the next step. 


The Auth process is simple, first, open user.php at ...\src\Model\Entity\User.php and add the codes to hash the password input. This is important to ensure that the password is hashed before it saves to the database. At the beginning of the file, add the following codes to use the default password hasher:

namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher; //Add this line
use Cake\ORM\Entity;


Then in the same file, add the public function _setPassword after class User extends Entity  to hashed the password:

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


At this point, you can try to create a new user and check the saved password should be hashed as follows:



Then load the Auth component in AppController.php at ...\src\Controller\AppController.php and add the following codes:

    public function initialize(): void
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');

        $this->loadComponent('Auth'); //Load auth component
        $this->Auth->allow(['login','add']); //Allow page


You also can add the Auth->allow later. The Auth component basically will block all pages and required an authentication session to access it. Using the Auth->allow method will allow the certain page that has been listed in the array to be accessible without authentication session. In this tutorial, I allowed login and add page. Next, create the login and logout function in user controller at ...\src\Controller\UsersController.php:

    public function login()
    {
        if($this->request->is('post')){
            $user = $this->Auth->identify();
            
            if($user){
                $this->Auth->setUser($user);
                return $this->redirect(['controller'=>'Users','action'=>'index']);
            }else {
                $this->Flash->error("Incorrect username or password !");
            }
        }
    }

    public function logout(){
        return $this->redirect($this->Auth->logout());
    }


Now, create the login.php file (create new) at ...\templates\Users and add the following codes:

<?= $this->Form->create() ?>
<?= $this->Form->control('username'); ?>
<?= $this->Form->control('password'); ?>
<?= $this->Form->submit() ?>
<?= $this->Form->end() ?>


Navigate to any controller eg: localhost/myCake4/users and it will redirect to the login page:



To create a new user, navigate to the localhost/myCake4/users/add (add and login is allowed in the Auth allow method) and register a new account if required. You also can create a new button to lead to the add page using this code:

<?php echo $this->Html->link(__('Register'), array('controller' => 'users', 'action' => 'add'), array('class' => 'button', 'escape' => false)); ?> 


To logout, navigate to localhost/myCake4/users/logout or create the logout button as follows:

<?php echo $this->Html->link(__('Logout'), array('controller' => 'users', 'action' => 'logout'), array('class' => 'button', 'escape' => false)); ?> 


That all. Happy coding :)