身份验证期间如何创建系统日志?

问题描述

我遵循此处的指南并实施了基本的身份验证系统: https://symfony.com/doc/current/security.html

但是,我想将系统日志添加到我的应用程序中。确切地说,我想要:

  • 能够插入与谁在什么时间成功登录的记录
  • 能够记录有人尝试登录并失败的时间

我知道我可以将日志放入我的SecurityController中,就像这样:

public function login(AuthenticationUtils $authenticationUtils,Request $request,EntityManagerInterface $em): Response
{
    // if ($this->getUser()) {
    //     return $this->redirectToRoute('target_path');
    // }

    $log = new Logs();
    $em->persist($log);

    $log->setAction('auth')
        ->setDate(new DateTime())
        ->setIp($request->getClientIp());

    $em->flush();

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig',['last_username' => $lastUsername,'error' => $error]);
}

但是它只给我有关某人在登录页面上的信息。如何修改或添加以获得其他信息?

解决方法

我认为这将解决您的问题。

您应该通过Symfony事件来做到这一点。失败/成功的登录尝试后,将触发以下两个事件:combined_key = "rateRequestPayments-0-amount" key,index,subkey = combined_key.split("-") del request_body[key][int(index)][subkey] security.authentication.success

我将举例说明成功,您可以将其应用于失败:

  1. 将此添加到您的security.authentication.failure

    config/service.yml
  2. 然后您可以创建侦听器并在其中进行日志记录过程

    App\EventListener\SuccessLoginListener:
    tags:
        - { name: 'kernel.event_listener',event: 'security.authentication.success'}
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...