cakephp - Auth.afterIdentify 没有触发
问题描述
我需要在用户会话启动后对其进行更改。这是暂时的,所以使用Auth.afterIdentify
我正在寻找的事件。
我试过的
- 我在很大程度上提到了这个关于如何解决这个问题的答案。
- 我尝试过使用匿名函数回调以及控制器回调方法
- 按照
Auth.afterIdentify
我添加的文档implementedEvents
- 确保
implementedEvents
有一个+ parent::implementedEvents()
,否则控制器一直向我显示主页
我有的
这是我目前的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 日志(即使有错误也没有),尽管它们正常工作。
我期望发生的事情
Log::write
在没有声明它来自哪里的情况下调用应该抛出(并记录)一个错误- 信息未
debug()
显示 - 删除该
public function afterIdentify
方法应该会导致错误;它没有——意味着控制器甚至没有在寻找它
解决方案
您正在混淆旧的身份验证组件和新的身份验证插件,该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);
}
);
}
推荐阅读
- azure-active-directory - Azure AD B2C 序列化 cookie 中的 StringCollection 声明
- python - 以 minio 作为后端的 Django-Storages S3
- javascript - React 应用程序上的响应式布局
- java - Spring-Data-Elasticsearch 在后台使用什么 Elasticsearch 客户端?
- docker - 后台进程运行时 Docker --rm 不清理
- c# - aspx.net 中的多个事件
- javascript - 条件循环可以根据其他值改变
- html - 更改具有不同跨度的列的边框间距
- api - 以协调的方式缓存来自外部 API 的数据
- ios - 从 Branch.io 响应中获取值并设置操作 (Swift)