Interview Questions

Spring Security - Count the login attempts

In Spring based web applications, it may be required to block a user, if he tries to login with invalid password more than "n" times.

This can be achieved if the application is configured with Spring Security framework.

We need to create an application listener as follows to trace the successful and failure login attempts.

import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;

public class AuthenticationListener implements ApplicationListener <AbstractAuthenticationEvent>
{
        @Override
        public void onApplicationEvent(AbstractAuthenticationEvent appEvent)
        {
            if (appEvent instanceof AuthenticationSuccessEvent)
            {
                AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
                // add code here to handle successful login event
            }

            if (appEvent instanceof AuthenticationFailureBadCredentialsEvent)
            {
                        AuthenticationFailureBadCredentialsEvent event = (AuthenticationFailureBadCredentialsEvent) appEvent;
                       
                        // add code here to handle unsuccessful login event
                        // for example, counting the number of login failure attempts and storing it in db
                        // this count can be used to lock or disable any user account as per business requirements
            }
        }
}