0

我正在使用 FosRestBundle、FosUserBundle 和 Lexik JWT 等工具开发 symfony restful api,用于 api 身份验证。

我需要将每个成功的登录信息保存在我的应用程序中。所以我创建了一个登录实体 (user_id,loginDate) ,但我不知道如何使用它,因为登录是从 Lexik 处理的。

有谁知道我该怎么做?

谢谢

4

1 回答 1

3

您可以security.interactive_login为此使用事件。更多信息可以从官方文档中找到: https ://symfony.com/doc/current/components/security/authentication.html#authentication-events

创建监听器并注册它:

namespace App\EventListener;

use App\Component\EntityManagerAwareTrait;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;

/**
 * @package App\EventListener
 */
class SecuritySubscriber implements EventSubscriberInterface
{
    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * @return array
     */
    public static function getSubscribedEvents(): array
    {
        return [
            SecurityEvents::INTERACTIVE_LOGIN => 'onSecurityInteractiveLogin',
        ];
    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event): void
    {
        $user = $event->getAuthenticationToken()->getUser();
        if ($user instanceof User) {
            $user->setLoginDate(new \DateTime());

            $this->em->persist($user);
            $this->em->flush();
        }
    }
}
于 2018-09-26T11:00:52.087 回答