Auth.afterIdentify 没有开火

Auth.afterIdentify is not firing

我需要在用户会话启动后更改一些内容。这是临时的,所以使用诸如 Auth.afterIdentify 之类的事件是我正在寻找的。

我试过的

我有什么

这是我当前的src/Controller/AppController.php

<?php
namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;

class AppController extends Controller implements \Cake\Event\EventListenerInterface
{

    public function initialize()
    {
        parent::initialize();

        // …

        $this->loadComponent('Authentication.Authentication');
        // Trying with an anonymous function
        \Cake\Event\EventManager::instance()->on('Auth.afterIdentify', function ($event) {
            Log::write( // noticed when posting this question, should have thrown an error
                'info',
                'Testing: ' . $event->getSubject()->id
            );
            debug($event);exit;
        });
        // Trying a controller callback
        \Cake\Event\EventManager::instance()->on('Auth.afterIdentify', [$this, 'afterIdentify']);
    }

    public function beforeFilter(\Cake\Event\Event $event)
    {
        parent::beforeFilter($event);
        $this->set('myAuth', $this->Authentication->getResult());
        $this->set('myUser', $this->Authentication->getIdentity());
    }

    public function afterIdentify(CakeEvent $cakeEvent, $data, $auth) {
        debug([
            '$cakeEvent' => $cakeEvent,
            '$data' => $data,
            '$auth' => $auth,
        ]);exit;
    }

    public function implementedEvents()
    {
        return [
            'Auth.afterIdentify' => 'afterIdentify',
        ] + parent::implementedEvents();
    }

}

什么不起作用

上面的事件监听器似乎都没有被调用。没有更新 CakePHP 日志(即使有错误也没有),尽管它们正常工作。

我预期会发生什么

您混淆了旧的身份验证组件和新的身份验证插件,Auth.afterIdentify 事件属于前者。

身份验证插件的身份验证组件有一个 Authentication.afterIdentify 事件,但这仅适用于有状态且不实现自动持久化的身份验证器。因此开箱即用,这仅适用于 Form 身份验证器,并且在通过表单对用户进行身份验证的请求中触发一次事件,在随后通过 [=14 对用户进行身份验证的请求中触发事件=] authenticator,事件没有被触发。

public function initialize()
{
    parent::initialize();

    // ...

    $this->loadComponent('Authentication.Authentication');

    $this->Authentication->getEventManager()->on(
        'Authentication.afterIdentify',
        function (
            \Cake\Event\EventInterface $event,
            \Authentication\Authenticator\AuthenticatorInterface $provider,
            \Authentication\IdentityInterface $identity,
            \Authentication\AuthenticationServiceInterface $service
        ) {
            // ...
            
            $identity['foo'] = 'bar';
            $this->Authentication->setIdentity($identity);
        }
    );
}