史上最简单的Spring Security教程(十):AuthenticationFailureHandler高级用法

论坛 期权论坛 脚本     
已经匿名di用户   2022-3-21 23:41   1896   0

在前面,我们简述了如何自定义用户登录失败页面。但是,在工作中,所遇到的业务场景压根不会这么简单。

比如要求记录登录失败时的IP、时间、SessionId;发送登录失败提醒到微信、邮箱、短信,提醒用户当前登录失败事件;同时记录到日志中,或者发送到远端日志监控平台,分析是否是攻击行为等等。

而这一切,Spring Security 框架非常贴心的提供了 AuthenticationFailureHandler 接口,当然了,框架同时也提供了一些简单的实现,最重要的,用户可自行扩展,以满足不同的业务场景。

这里,我们模拟发送信息提醒、记录日志操作,对 AuthenticationFailureHandler 接口进行扩展。

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    super.onAuthenticationFailure(request, response, exception);

    this.logger.info(String.format("IP %s 于 %s 尝试登录系统失败,失败原因:%s", request.getRemoteHost(), LocalDateTime.now(), exception.getMessage()));

    try {
        // 发邮件
        this.emailService.send();

        // 发短信
        this.smsService.send();

        // 发微信
        this.weChatService.send();
    } catch (Exception ex) {
        this.logger.error(ex.getMessage(), ex);
    }
}

Spring Security 配置调整:

......
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        ......
        .failureHandler(customSimpleUrlAuthenticationFailureHandler())
        .permitAll()
        .and()
        .authorizeRequests()
        .antMatchers("/login_fail").permitAll()
        ......
}

public AuthenticationFailureHandler customSimpleUrlAuthenticationFailureHandler() {
    CustomSimpleUrlAuthenticationFailureHandler customSimpleUrlAuthenticationFailureHandler = new CustomSimpleUrlAuthenticationFailureHandler();
    customSimpleUrlAuthenticationFailureHandler.setDefaultFailureUrl("/login_fail");
    customSimpleUrlAuthenticationFailureHandler.setEmailService(emailService);
    customSimpleUrlAuthenticationFailureHandler.setSmsService(smsService);
    customSimpleUrlAuthenticationFailureHandler.setWeChatService(weChatService);

    return customSimpleUrlAuthenticationFailureHandler;
}
......

启动系统,登录,然后故意输错密码,系统跳转到了登录失败页面。

同时,查看控制台,日志也记录了本次登录失败的一些信息;同时,提醒信息也同步发送到了用户的邮箱、短信、微信,告知用户本次登录失败事件详情。

其它详细源码,请参考文末源码链接,可自行下载后阅读。

源码

github

https://github.com/liuminglei/SpringSecurityLearning/tree/master/10

gitee

https://gitee.com/xbd521/SpringSecurityLearning/tree/master/10

回复以下关键字,获取更多资源

SpringCloud进阶之路 | Java 基础 | 微服务 | JAVA WEB | JAVA 进阶 | JAVA 面试 | MK 精讲

笔者开通了个人微信公众号【银河架构师】,分享工作、生活过程中的心得体会,填坑指南,技术感悟等内容,会比博客提前更新,欢迎订阅。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP