我在cakephp4中使用身份验证(2)插件。 我已经设置了:
'unauthenticatedRedirect' => '/users/login',
以便重定向需要身份验证的请求。很好。
但是我想添加一条消息,例如Flash消息,内容为“您必须登录才能访问此页面”。
有一种简单的方法吗?
谢谢
答案 0 :(得分:1)
尚无特定功能: https://github.com/cakephp/authentication/issues/316
可以通过许多不同的方式解决此问题,我个人之前通过将Authentication\Authenticator\UnauthenticatedException
捕获在扩展的身份验证组件中,通过覆盖\Authentication\Controller\Component\AuthenticationComponent::doIdentityCheck()
来做到这一点:
<?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.');
}
}