java - Spring Security 未捕获 ApplicationListener 中的登录失败

标签 java spring spring-mvc spring-security

我正在使用 Spring Security 3.2.5.RELEASE,并且很难捕获失败的登录尝试。我目前有一个 ApplicationListener 配置如下:

@Component
public class MyApplicationListener implements ApplicationListener<AbstractAuthenticationEvent> {

    private static Logger logger = LogManager.getLogger(MyApplicationListener);

    @Override
    public void onApplicationEvent(AbstractAuthenticationEvent abstractAuthenticationEvent) {

        if (abstractAuthenticationEvent instanceof AbstractAuthenticationFailureEvent) {

            logger.warn("Detected an invalid login");

        } else if (abstractAuthenticationEvent instanceof AuthenticationSuccessEvent) {

            logger.info("A user logged in successfully");
        }
    }
}

如果用户成功登录,我可以按预期看到成功消息。但是,如果用户提供了错误的密码等,则永远不会显示失败消息。

我更改了监听器,以便它记录所有 ApplicationEvent,如下所示:

@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

    private static Logger logger = LogManager.getLogger(MyApplicationListener);

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {

        logger.info("Got an event of type {}", applicationEvent.getClass());
    }
}

但是,记录的唯一与安全相关的事件的类型为org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent。登录失败不会触发任何事件。我将不胜感激任何指点,谢谢。

最佳答案

也许有点晚了,但我遇到了同样的问题并以这种方式解决:

在您的configureGlobal方法中: auth.authenticationEventPublisher(defaultAuthenticationEventPublisher());

不要忘记将 DefaultAuthenticationEventPublisher 声明为 Bean

@Bean
public DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(){
    return new DefaultAuthenticationEventPublisher();
}

更多信息请点击这里: Why the event AbstractAuthenticationFailureEvent is never triggered in spring security?

关于java - Spring Security 未捕获 ApplicationListener 中的登录失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27879957/

相关文章:

java - Tomcat Embedded 启动时出错

java - Spring Security 注销和最大 session 数

java - 将字符串数组索引值替换为另一个值

java - 使用代理记录 jmeter 请求不会创建采样器

java - 表单中的 LocalDate

java - 如何调用使用 BeanLocator 找到的对象上的方法

java - 无法加载Spring Web应用程序的ApplicationContext

java - hasPermission 的第一个参数的含义是什么?

java - 为什么我不能将 SparseArray 转换为数组?

java - Tomcat 不读取 web.xml 文件