我想使用security.interactive_login
更新我的用户的上次登录字段的事件。
活动注册成功:
php bin/console debug:event-dispatcher security.interactive_login
Registered Listeners for "security.interactive_login" Event
===========================================================
------- ------------------------------------------------------------------------ ----------
Order Callable Priority
------- ------------------------------------------------------------------------ ----------
#1 App\EventSubscriber\UserLocaleSubscriber::onSecurityInteractiveLogin() 0
------- ------------------------------------------------------------------------ ----------
但它降落在不称为听众在 Symfony 分析器中。
这是事件订阅者:
class UserLocaleSubscriber implements EventSubscriberInterface
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
/** @var User $user */
$user = $event->getAuthenticationToken()->getUser();
$user->setLastLoginAt(new DateTime());
$this->em->persist($user);
$this->em->flush();
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
];
}
}
还有我的安全.yaml file:
security:
enable_authenticator_manager: true
encoders:
App\Entity\User:
algorithm: auto
providers:
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js|fonts)/
security: false
main:
lazy: true
provider: app_user_provider
guard:
authenticators:
- App\Security\LoginAuthenticator
logout:
path: app_logout
target: app_login # where to redirect after logout
remember_me:
secret: '%kernel.secret%'
lifetime: 604800 # 1 week in seconds
path: /
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
# Note: Only the *first* access control that matches will be used
access_control:
- { path: ^/(?!login), roles: ROLE_ADMIN }
The 登录验证器class 是 Symfony 默认生成的类。
Why the 交互式登录事件没有被调用?
当使用新的身份验证管理器时,INTERACTIVE_LOGIN
事件被替换为LoginSuccessEvent
.
# my subscriber
public static function getSubscribedEvents()
{
return [
//SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
LoginSuccessEvent::class => 'onLoginSuccess'
];
}
public function onLoginSuccess(LoginSuccessEvent $event)
{
$user = $event->getUser();
$user->setCount($user->getCount() + 1);
$this->em->flush();
//dd($user);
}
我不确定这是否已明确记录。与许多升级弃用一样,代码非常混乱。我试图追踪正在发生的事情,但很快(再次)在安全森林中迷路了。
事件被谈论here https://symfony.com/blog/new-in-symfony-5-1-updated-security-system.
我通过创建一个新的 5.1 项目发现了这种行为,运行make:auth
并为这两个事件添加监听器。但我忘记将enable_authenticator_manager: true 添加到安全配置中。
So the INTERACTIVE_LOGIN
事件被解雇。启用新管理器后,LoginSuccessEvent
被解雇。请注意,新事件有一些附加的辅助方法,例如 getUser。使代码更加干净一点。
偏离主题,但我会警告不要刷新侦听器内的实体管理器。根据其他情况的不同,这可能有点难以预测。可能会考虑仅获取数据库连接并执行 SQL 更新。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)