簡體   English   中英

Symfony 安全性:當用戶從會話中進行身份驗證時是否存在事件?

[英]Symfony security: Is there an event when a user is authenticated from the session?

當 Symfony 對會話中的用戶進行身份驗證時,是否有任何事件? LoginSuccessEvent似乎只在交互式登錄期間被觸發,例如在使用登錄表單時而不是在為已經登錄的用戶加載新頁面時。

細節:

我正在開發一個基於 Symfony 6.1 的項目,我按照 Symfony 文檔中的說明(例如此處此處)來構建基於用戶類和登錄表單的安全性。

一切正常:對受限頁面的訪問被防火牆阻止,用戶被重定向到他可以登錄的登錄表單。 登錄后,可以訪問所有頁面,直到登錄過期。

提交登錄表單后,會觸發LoginSuccessEvent 但是,當使用會話中的用戶加載新頁面時,不會觸發此事件。 這種身份驗證是否還有其他安全事件? 我在文檔中發現的所有事件似乎都不適用於這種情況。

實際上,該事件僅在登錄時執行一次。 或者,您可以創建一個kernel.request事件,該事件將在每個請求時觸發。 在這種情況下,您可以將 Security 組件傳遞給構造函數參數並獲取當前用戶並執行必要的操作

use App\Entity\User;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Security;

class UserListener
{

    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $user = $this->security->getUser();
        if (!$event->getRequest()->isXmlHttpRequest() and $user instanceof User){
            // do something ...
            dump($user);
        }
    }
}

在 services.yaml 中注冊監聽器

App\EventListener\UserListener:
    tags:
        - {name:  kernel.event_listener, event: kernel.request }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM