Spring security 自定义成功和失败的处理器使用EventPublisher 方式

需求:用户获取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());
    }
}

收录爱图一张



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值