CakePHP 4 Authentication – Tutorial


CakePHP 4 Authentication

CakePHP 4 Authentication tutorial, we will learn a way to use this plugin, how to install and configure it in our applications

CakePHP 4 Authentication – Plugin

We will start this tutorial by installing the package with composer

composer require "cakephp/authentication:^2.0"

Once the package is installed we proceed to add the codes in the relevant areas, first we add the component in the AppController.php file

namespace App\Controller;

use Cake\Controller\Controller;

class AppController extends Controller
{   
    public function initialize(): void
    {
        parent::initialize();

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

    
        $this->loadComponent('Authentication.Authentication');
    }
}

We continue with the next step, now we go to the Application.php file and we import the following classes, pay attention where there is a duplicate class in our code


use Authentication\AuthenticationService;
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Authentication\Identifier\IdentifierInterface;
use Authentication\Middleware\AuthenticationMiddleware;
use Cake\Routing\Router;
use Psr\Http\Message\ServerRequestInterface;

We continue now with the implementation of interfaces

class Application extends BaseApplication implements AuthenticationServiceProviderInterface

It’s time to add the authentication plugin

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

        if (PHP_SAPI === 'cli') {
            $this->bootstrapCli();
        } else {
            FactoryLocator::add(
                'Table',
                (new TableLocator())->allowFallbackClass(false)
            );
        }
       
        if (Configure::read('debug')) {
            $this->addPlugin('DebugKit');
        }
       
        $this->addPlugin('Authentication');
       
    }

We add the relevant middleware to execute the application logic

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
    {
        $middlewareQueue
           
        ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
          
        ->add(new AssetMiddleware([
            'cacheTime' => Configure::read('Asset.cacheTime'),
        ]))
           
        ->add(new RoutingMiddleware($this))
         
        ->add(new BodyParserMiddleware())

        ->add(new AuthenticationMiddleware($this))  

        ->add(new CsrfProtectionMiddleware([
            'httponly' => true,
        ]));

        return $middlewareQueue;
    }

We continue adding the method that allows us to authenticate

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

   
        $service->setConfig([
            'unauthenticatedRedirect' => Router::url([
                'prefix' => false,
                'plugin' => null,
                'controller' => 'Users',
                'action' => 'login',
            ]),
            'queryParam' => 'redirect',
        ]);

  
        $fields = [
            IdentifierInterface::CREDENTIAL_USERNAME => 'username',
            IdentifierInterface::CREDENTIAL_PASSWORD => 'password'
        ];
 
        $service->loadAuthenticator('Authentication.Session');
        $service->loadAuthenticator('Authentication.Form', [
            'fields' => $fields,
            'loginUrl' => Router::url([
                'prefix' => false,
                'plugin' => null,
                'controller' => 'Users',
                'action' => 'login',
            ]),
        ]);
 
        $service->loadIdentifier('Authentication.Password', compact('fields'));

        return $service;
    }

We add the credentials with which we want to log in, the options are username or email