CakePHP 5 custom authentication, PasswordHasher

I would try something like this:

create: src/Authentication/PasswordHasher/PhpassPasswordHasher.php

<?php
namespace App\Authentication\PasswordHasher;

use Authentication\PasswordHasher\AbstractPasswordHasher;

class PhpassPasswordHasher extends AbstractPasswordHasher
{
    public function hash($password)
    {
        // your code
        return 'xyz';
    }

    public function check($password, $hashedPassword)
    {
        // your code
        return true;
    }
}

@ User Entity:

namespace App\Model\Entity;

use Cake\ORM\Entity;
use App\Authentication\PasswordHasher\PhpassPasswordHasher;

class User extends Entity
{
    protected function _setUserPass(string $password) : ?string
    {
        if (strlen($password) > 0) {
            return (new PhpassPasswordHasher())->hash($password);
        }
        return null;
    }
}

@ src/Application.php

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

    // Load identifiers
    $service->loadIdentifier('Authentication.Password', [
        'fields' => [
            'username' => 'user_login',
            'password' => 'user_pass'
        ]
    ]);

    // Load the authenticators
    $service->loadAuthenticator('Authentication.Session');
    $service->loadAuthenticator('Authentication.Form', [
        'fields' => [
            'username' => 'user_login',
            'password' => 'user_pass'
        ],
        'loginUrl' => '/users/login'
    ]);

    // Using the custom password hasher
    $service->setConfig([
        'passwordHasher' => [
            'className' => PhpassPasswordHasher::class
        ]
    ]);

    return $service;
}

PS, I haven’t tested the code.

2 Likes