<?php
// src/Controller/Component/AppAuthenticationComponent.php
/*
load in `AppController::initialize()` via:
$this->loadComponent('Authentication', [
'className' => \App\Controller\Component\AppAuthenticationComponent::class,
]);
* /
namespace App\Controller\Component;
use Authentication\Authenticator\UnauthenticatedException;
use Authentication\Controller\Component\AuthenticationComponent;
use Cake\Controller\Component\FlashComponent;
/**
* @property FlashComponent $Flash
*/
class AppAuthenticationComponent extends AuthenticationComponent
{
public $components = [
'Flash'
];
protected function doIdentityCheck(): void
{
try {
parent::doIdentityCheck();
} catch (UnauthenticatedException $exception) {
$this->Flash->error(__('You must be logged in to access this page.'));
throw $exception;
}
}
}
您也可以在应用控制器中手动执行此操作,为此,您必须禁用插件组件的自动身份检查,并自行执行该检查:
// src/Controller/AppController.php
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Authentication.Authentication', [
'requireIdentity' => false
]);
}
public function beforeFilter(EventInterface $event)
{
parent::beforeFilter($event);
$action = $this->request->getParam('action');
if (
!in_array($action, $this->Authentication->getUnauthenticatedActions(), true) &&
!$this->Authentication->getIdentity()
) {
$this->Flash->error(__('You must be logged in to access this page.'));
throw new UnauthenticatedException('No identity found.');
}
}
1条答案
按热度按时间r7xajy2e1#
目前还没有具体的功能:******
它可以用许多不同的方法来解决,我个人以前已经这样做了,通过在扩展的身份验证组件中捕获
Authentication\Authenticator\UnauthenticatedException
,通过覆盖\Authentication\Controller\Component\AuthenticationComponent::doIdentityCheck()
:您也可以在应用控制器中手动执行此操作,为此,您必须禁用插件组件的自动身份检查,并自行执行该检查: