Skip to content
CODE THE PIXEL
CakePHP

CakePHP 4 Authentication Using Auth Component (Basic)

Asyraf Wahi Anuar Updated 4 min read

This tutorial will show how to use the Auth component to create an authentication in CakePHP

This tutorial may be outdated

It was last reviewed 4 years ago. Some steps may differ in newer versions.

Tech stack

  • CakePHP 4.x

This tutorial will show how to use the Auth component to create an authentication in CakePHP. Download the CakePHP (refer to CakePHP 4 installation tutorial) and create your database with the user's 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:

src/Model/Entity/User.phpPHP
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:

src/Controller/AppController.phpPHP
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 an authentication session. In this tutorial, I allowed login and add page. Next, create the login and logout function in the user controller at ...\src\Controller\UsersController.php:

src/Controller/UsersController.phpPHP
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:

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

That all. Happy coding :)

Did this tutorial help?

240 readers found this helpful

Comments

No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

CakePHP 4 Log User Authentication Using Component

This tutorial will discuss how to create a user activities log using the CakePHP component. The basic activities that will be logged are the authentication method which includes the login and logout details.

3 min read

CakePHP

CakePHP 4 Auth Using CakeDC User Plugin

Authentication and authorization are critical components in the protection of online application content. They validate the user's identification and give access to the resources.

8 min read

CakePHP

CakePHP 4 Authentication Using Auth Component (Advance)

This tutorial will show how to create an authentication using the Auth component for CakePHP 4. It includes the process of password hashing, registration with email verification, multi-field username/email login, forgot password, reset password and status management.

10 min read