需求:用户获取token之后如果成功则记录用的登录IP, 登录次数, 最后一次登录时间等信息, 如果登录失败记录登录失败次数。
问题:由于使用spring security 做的鉴权, 登个登录成功之后好说, 但是失败之后直接抛了一个异常, 导致不知道在哪里改记录失败的操作, 可以在adivce 中监听这个异常, 但是不好获取request 用户等信息, 且这样做感觉也不合适。
解决:开始参考了这篇博文, https://zhuanlan.zhihu.com/p/35480689, 写两个handler 然后在 Config 中 调用httpSecurity.formLogin().successfulHandler() 方法, 然后在我这里并不管用, 而且不能这样做, 因为项目中集成jwtToken , 压根就没有表单。在查看源码的过程中, 发现providerManager 中有一个 ApplicationEventListener 的属性, 尝试自己写一个实现类集成他默认实现类, 然后调用
authenticationManagerBuilder
.authenticationEventPublisher()
然而发现并不行, 啥原因现在也不是很清楚
最后从http://lengyun3566.iteye.com/blog/1273185这篇博文看到注入EventPublisher 的方式, 发现有用
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.stereotype.Component;
@Component
public class CustomAuthenticationEventListener implements ApplicationListener<AbstractAuthenticationEvent> {
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
System.out.println("Received event of type: "+event.getClass().getName()+": "+event.toString());
}
}
收录爱图一张