2008-10-08 60 views
32

我是Spring Security的新手。我如何添加一個事件監聽器,這個監聽器將在用戶成功登錄時被調用?此外,我需要在此偵聽器中獲得某種唯一的會話ID,該ID應該可以繼續使用。我需要這個ID來與另一臺服務器同步。春季安全:添加「成功登錄事件監聽器」

回答

41

您需要定義一個實現了ApplicationListener的Spring Bean。

然後,在你的代碼,做這樣的事情:

public void onApplicationEvent(ApplicationEvent appEvent) 
{ 
    if (appEvent instanceof AuthenticationSuccessEvent) 
    { 
     AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent; 
     UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); 

     // .... 
    } 
} 

然後,在你的applicationContext.xml文件,只是定義的bean,它會自動開始接收事件:)

+0

謝謝!剛剛找到AuthenticationSuccessEvent,但試圖找出如何註冊一個監聽器。 – axk 2008-10-08 12:36:35

+2

他詢問的會話ID如何? – siebmanb 2015-02-26 10:28:29

+1

@siebmanb只需向偵聽器添加「@Autowired HttpSession會話」即可。 Spring將注入一個自動委託給更正會話的代理。 – 2016-02-17 22:43:11

10

Grails中使用Spring安全插件,您可以在Config.groovy中做到這一點:

grails.plugins.springsecurity.useSecurityEventListener = true 

grails.plugins.springsecurity.onAuthenticationSuccessEvent = { e, appCtx -> 

     def session = SecurityRequestHolder.request.getSession(false) 
     session.myVar = true 

} 
21

類似菲爾的回答,但修改以泛型考慮:

public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> { 

    @Override 
    public void onApplicationEvent(final AuthenticationSuccessEvent event) { 

     // ... 

    } 

} 
38

AuthenticationSuccessEvent的問題是它不會在記住我登錄時發佈。如果您使用記憶式身份驗證,請改用InteractiveAuthenticationSuccessEvent,它適用於正常登錄以及記住我登錄。

@Component 
public class LoginListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> { 

    @Override 
    public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) 
    { 
     UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); 
     // ... 
    } 
}