史上最简单的Spring Security教程(五):成功登录SuccessHandler高级用法

 

在了解了如何简单的配置成功登录后调转的页面、如何始终指定系统跳转到某一地址后,我们可能会庆幸,原来如此简单。是的,确实如此简单,Spring Security 框架协助我们完成了大部分的工作,而我们只需稍微配置,即可使用。

但是,业务场景,又何尝会如此简单。举个例子,我们在登录某个网站之后,微信、短信、邮箱可能会接受到一条这样的信息/邮件。

还有,比如这样的。

甚至于,我要记录每一次的登录信息到数据库、到日志文件等等,方便后续做审计、分析。

其实,Spring Security 框架也可以很方便的做这些事情。这都是登录成功后才提醒用户的,那么我们就可以在登录成功后的 SuccessHandler 上面下下功夫。

......
    
http.formLogin().successHandler(customAuthenticationSuccessHandler())
    
@Bean
public AuthenticationSuccessHandler customAuthenticationSuccessHandler() {
    CustomSavedRequestAwareAuthenticationSuccessHandler customSavedRequestAwareAuthenticationSuccessHandler = new CustomSavedRequestAwareAuthenticationSuccessHandler();
    customSavedRequestAwareAuthenticationSuccessHandler.setEmailService(emailService);
    customSavedRequestAwareAuthenticationSuccessHandler.setSmsService(smsService);
    customSavedRequestAwareAuthenticationSuccessHandler.setWeChatService(wechatService);
    return customSavedRequestAwareAuthenticationSuccessHandler;
}
​
......

 

自定义的 CustomSavedRequestAwareAuthenticationSuccessHandler 逻辑也很简单,只是发送消息,至于消息内容,可以任何想获得的信息,因为参数有 HttpServletRequest 、Authentication,可以获取比较的内容;而其也继承于 SavedRequestAwareAuthenticationSuccessHandler,天然地拥有了 Request 缓存、targetUrl 判断等特性。

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
    super.onAuthenticationSuccess(request, response, authentication);
​
    this.logger.info(String.format("IP %s,用户 %s, 于 %s 成功登录系统。", request.getRemoteHost(), authentication.getName(), LocalDateTime.now()));
    
    try {
        // 发邮件
        this.emailService.send();
​
        // 发短信
        this.smsService.send();
​
        // 发微信
        this.weChatService.send();
    } catch (Exception ex) {
        this.logger.error(ex.getMessage(), ex);
    }
}

 

当然,想往其它服务,比如分布式、微服务组件发送信息,也是可以的。只需要在该类中注入相关实例,即可发送相关信息。

启动系统,登录成功后,控制台成功打印了相关信息。

至于设计模式、开发原则等内容,不是本文考虑的内容,我们不做考虑,以简单为第一要旨。

源码

github

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

gitee

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

 

 

 

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

 

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

 

 

 

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

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值