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

后端 未结 7 2273
情书的邮戳
情书的邮戳 2020-12-23 18:31

We\'re using spring security 3.0.5, Java 1.6 and Tomcat 6.0.32. In our .xml config file we\'ve got:



        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-23 19:12

    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 {
        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.

提交回复
热议问题