2015-09-28 40 views
2

雖然環顧使用AuthenticationHandlers,但我看到Symfony支持EventSubscribers,當使用多種方法進行身份驗證時,它可以更靈活。是否可以在Silex中使用EventSubscribers?

我一直用這個作爲一個例子:https://knpuniversity.com/screencast/guard/success-handling

所以,我有我的用戶類的所有設置,但我不知道該怎麼辦是寄存器在Silex的事件。

我很確定我需要使用$app['dispatcher']但我不知道是什麼事件聽。使用示例從頁,在Symfony的配置,SERVICS被打上kernel.event_subscriber但是當我做了在Silex的任何以下事情:

$app['dispatcher'] -> addListener(KernelEvents::EVENT_SUBSCRIBER, function(Event $event) use ($app) { ... do something ... });

我敢肯定,我監聽的事件是錯誤的,但我也沒有得到任何錯誤。在Silex中這種事情是可能的嗎?

感謝,羅素

更新:

這是我的用戶等級:

<?php 

namespace MySubscriber; 

use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; 
use Symfony\Component\Security\Http\SecurityEvents; 

class ApiKeySubscriber implements EventSubscriberInterface { 

    public function onInteractiveLogin(InteractiveLoginEvent $event) { 

    file_put_contents("/tmp/onInteractiveLogin.txt", "It was ehere"); 

    } 

    public static function getSubscribedEvents() { 
    return array(SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin'); 
    } 
} 

防火牆是非常簡單的:

// Configure the firewalls for the application 
    $app['security.firewalls'] = array(
     'basicauth' => array(
      'pattern' => '^/auth', 
      'http' => true, 
      'users' => $app -> share(function() use ($app) { 
       return new UserAccount($app); 
      }) 
     ) 
    ); 

然後我添加訂戶:

$app['dispatcher'] -> addSubscriber(new \MySubscriber\ApiKeySubscriber()); 

我假設Basic Auth被認定爲交互式登錄,所以我不確定爲什麼該方法沒有被調用。

回答

2

您的訂戶類應執行EventSubscriberInterface。如果是這樣,只需使用addSubscriber方法而不是addListener

$app['dispatcher']->addSubscriber(new MyEventSubscriber()); 

你的活動用戶有一個名爲getSubscribedEvents方法,告訴Symfony的訂閱什麼事件,所以你並不需要在所有通過事件名稱。有關更多信息,請參見the Symfony docs

更新(安全聽衆):

基本的HTTP認證方法不被認爲是交互式登錄。這是一個典型的基於Web的登錄表單。

您或許可以使用AuthenticationEvents::AUTHENTICATION_SUCCESS。您的偵聽器方法將收到一個AuthenticationEvent實例。

<?php 
namespace MySubscriber; 

use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\Security\Core\AuthenticationEvents; 
use Symfony\Component\Security\Core\Event\AuthenticationEvent; 

class ApiKeySubscriber implements EventSubscriberInterface 
{ 
    public function onAuthenticate(AuthenticationEvent $event) 
    { 
    file_put_contents("/tmp/onInteractiveLogin.txt", "It was here"); 
    } 

    public static function getSubscribedEvents() 
    { 
    return array(AuthenticationEvents::AUTHENTICATION_SUCCESS => 'onAuthenticate'); 
    } 
} 
+0

謝謝你的說法,這很有道理。我的訂戶確實實現了EventSubscriberInterface,我已經更新了我的答案。我不確定的是爲什麼'onInteractiveLogin'沒有被調用。我沒有得到正在創建的文件。我正在使用具有基本身份驗證的防火牆。 –

+0

更新了安全監聽信息 –

+0

非常感謝,我會稍後再試。如果'基本認證'不被認爲是一個交互式登錄,對於SuccessHandlers來說同樣適用嗎?我一直試圖讓它使用HTTP認證,但懷疑這不被支持,這將解釋爲什麼我的SuccessHandler不能正常工作。我明白處理程序和訂戶是不同的東西,我可能不需要兩者。 –

相關問題