There are many situations when we are required to listen for successful login event. To store last login information, to manage some post login account handling … it’s quite easy to do by following Spring Boot way.
Spring Boot internals gather application listener beans (we must inherit ApplicationListener<InteractiveAuthenticationSuccessEvent> here and annotate as @Component) during startup. Such simple bean and configuration (see code below) causes Spring Boot to call my listener and provide me with authenticated user’s details. And this is what I just needed!
This little post is just a reminder for me, that such listener is invoked for form authentication only and doesn’t run when basic authentication enabled. It hopefully avoids some headaches in future!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package app.config; import org.springframework.context.ApplicationListener; import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; @Component public class LoginListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> { @Override public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) { UserDetails user = (UserDetails) event.getAuthentication().getPrincipal(); System.out.println("LOGIN name: "+user.getUsername()); } } |