Tags

Jul 5, 2011

Locking user account after max login attempts

Locking user account after max login attempts

@Component
     public class CustomAuthenticationEventListener implements
           ApplicationListener
     {
     public void onApplicationEvent(AbstractAuthenticationEvent event)
              throws LockedException {
           if (event instanceof AuthenticationFailureBadCredentialsEvent) {
              String username = event.getAuthentication().getName();
              UserDTO user = userService.getUserDetails(username);
              if (user != null) {
     int failedLoginAttempts =       user.getFailedLoginAttempts();
     userService.setLoginCounter(username, ++failedLoginAttempts);
     if (failedLoginAttempts == UserDTO.getMaxFailedLoginAttempts()) {
     throw new LockedException(messageSource.getMessage(
     "security.login.form.locked", null, null));
                 }
              }
           }
           if (event instanceof AuthenticationSuccessEvent) {
              String username = event.getAuthentication().getName();
              UserDTO user = userService.getUserDetails(username);
              if (user != null) {
                 userService.setLoginCounter(username, 0);
              }
           }      
        }
     } 

1 comment: