2015-01-10 41 views
2

我正在使用Spring Security 3.2.5.RELEASE,並且難以捕獲失敗的登錄嘗試。我現在有一個ApplicationListener配置如下:Spring Security沒有捕獲ApplicationListener中的登錄失敗

@Component 
public class MyApplicationListener implements ApplicationListener<AbstractAuthenticationEvent> { 

    private static Logger logger = LogManager.getLogger(MyApplicationListener); 

    @Override 
    public void onApplicationEvent(AbstractAuthenticationEvent abstractAuthenticationEvent) { 

     if (abstractAuthenticationEvent instanceof AbstractAuthenticationFailureEvent) { 

      logger.warn("Detected an invalid login"); 

     } else if (abstractAuthenticationEvent instanceof AuthenticationSuccessEvent) { 

      logger.info("A user logged in successfully"); 
     } 
    } 
} 

如果成功用戶登錄我可以看到成功的消息符合市場預期。但是,如果用戶提供了錯誤的密碼等,則失敗消息從不顯示。

我改變了偵聽器,使其如下記錄所有ApplicationEvent

@Component 
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> { 

    private static Logger logger = LogManager.getLogger(MyApplicationListener); 

    @Override 
    public void onApplicationEvent(ApplicationEvent applicationEvent) { 

     logger.info("Got an event of type {}", applicationEvent.getClass()); 
    } 
} 

但是所記錄的唯一安全相關的事件是org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent類型。失敗的登錄不會觸發任何事件。我將不勝感激任何指針,謝謝。

回答

3

也許是有點晚了,但我得到了同樣的問題,解決這個問題是這樣的:

在你configureGlobal方法: auth.authenticationEventPublisher(defaultAuthenticationEventPublisher());

不要忘記申報DefaultAuthenticationEventPublisher作爲一個Bean

@Bean 
public DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(){ 
    return new DefaultAuthenticationEventPublisher(); 
} 

更多的信息: Why the event AbstractAuthenticationFailureEvent is never triggered in spring security?