Spring security: adding “On successful login event listener”

情到浓时终转凉″ 提交于 2019-12-28 02:32:15

问题


I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.


回答1:


You need to define a Spring Bean which implements ApplicationListener.

Then, in your code, do something like this:

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

        // ....
    }
}

Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)




回答2:


The problem with AuthenticationSuccessEvent is it doesn't get published on remember-me login. If you're using remember-me authentication use InteractiveAuthenticationSuccessEvent instead, it works for normal login as well as for remember-me login.

@Component
public class LoginListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {

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



回答3:


Similar to Phill's answer, but modified to take Generics into consideration:

public class AuthenticationListener implements ApplicationListener<AuthenticationSuccessEvent> {

  @Override
  public void onApplicationEvent(final AuthenticationSuccessEvent event) {

      // ...

  }

}



回答4:


In Grails, with Spring Security Plugin, you can do this in Config.groovy:

grails.plugins.springsecurity.useSecurityEventListener = true

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

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

}



回答5:


Another way using @EventListener

@EventListener
public void doSomething(InteractiveAuthenticationSuccessEvent event) { // any spring event
    // your code 

}


来源:https://stackoverflow.com/questions/182160/spring-security-adding-on-successful-login-event-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!