首页 > 解决方案 > Auth.afterIdentify 没有触发

问题描述

我需要在用户会话启动后对其进行更改。这是暂时的,所以使用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 日志(即使有错误也没有),尽管它们正常工作。

我期望发生的事情

标签: cakephpcakephp-3.0

解决方案


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

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

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);
        }
    );
}

推荐阅读