This is my approach to do this :
in config/routes.php
$routes->prefix(
'Backend',
['path' => '/gestion', '_namePrefix' => 'backend:'],
function (RouteBuilder $builder) {
$authenticationService = new AuthenticationService();
$fields = [
IdentifierInterface::CREDENTIAL_USERNAME => 'email',
IdentifierInterface::CREDENTIAL_PASSWORD => 'password',
];
$authenticationService->loadAuthenticator(SessionAuthenticator::class);
$authenticationService->loadAuthenticator(FormAuthenticator::class, [
'fields' => $fields,
'loginUrl' => ['_name' => 'backend:auth:login'],
]);
$builder->registerMiddleware('authentication', new AuthenticationMiddleware($authenticationService));
$builder->applyMiddleware('authentication');
In your Prefix App Controller:
public function initialize(): void
{
parent::initialize();
$service = $this->request->getAttribute('authentication');
$service->setConfig([
'unauthenticatedRedirect' => Router::url(['_name' => 'backend:auth:login']),
'queryParam' => 'r',
]);
$this->loadComponent('Authentication.Authentication');
}
You can use one AuthenticationService by prefix, configured as you want.