How can I get the username from a failed login using spring security?

You could instead supply your own version of DefaultAuthenticationEventPublisher and override the publishAuthenticationFailure method.


I did it this way:

  1. Created a class that extends SimpleUrlAuthenticationFailureHandler

  2. Overrid the onAuthenticationFailure method, which receives an HttpServletRequest as a parameter.

  3. request.getParameter("username"), where "username" is the name of my input in my HTML form.


Okay so the answer turned out to be something extremely simple yet as far as I can tell, not greatly discussed or documented.

Here's all I had to do (no configurations anywhere just created this class)...

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
    private static final Logger LOG = Logger.getLogger(MyApplicationListener.class);

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        Object userName = event.getAuthentication().getPrincipal();
        Object credentials = event.getAuthentication().getCredentials();
        LOG.debug("Failed login using USERNAME [" + userName + "]");
        LOG.debug("Failed login using PASSWORD [" + credentials + "]");
    }
}

I'm far from a spring security expert so if anyone reads this and knows of a reason we shouldn't do it like this or knows a better way I'd love to hear about it.