Thumbnail image

Spring Boot: Login Listener

Wed, Mar 13, 2019 One-minute read

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 a listener is invoked for form authentication only and doesn’t run when basic authentication enabled. It hopefully avoids some headaches in future!

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());
  }
}