2008-10-08 113 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(); 
     // ... 
    } 
}