cakephp 4 - authentication 2 -如何在未识别时显示消息

0sgqnhkj  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(166)

我使用cakephp4的身份验证(2)插件。我已经设置:

'unauthenticatedRedirect' => '/users/login',

以便重定向需要身份验证的请求。它工作正常。
但我想添加一条消息,例如一条快速消息,它会说“您必须登录才能访问此页面”。
有简单的方法吗?
谢谢

r7xajy2e

r7xajy2e1#

目前还没有具体的功能:******
它可以用许多不同的方法来解决,我个人以前已经这样做了,通过在扩展的身份验证组件中捕获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.');
    }
}

相关问题