Spring security: adding "On successful login event listener"

axk picture axk · Oct 8, 2008 · Viewed 38.2k times · Source

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.

Answer

user7094 picture user7094 · Oct 8, 2008

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 :)