史上最简单的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 精讲
笔者开通了个人微信公众号【银河架构师】,分享工作、生活过程中的心得体会,填坑指南,技术感悟等内容,会比博客提前更新,欢迎订阅。
上一篇: 内容营销十大趋势
下一篇: 网站运营如何定义用户价值
推荐阅读
-
史上最简单的Spring Security教程(十一):url区分不同的登录失败场景
-
史上最简单的Spring Security教程(七):用户登出成功url配置
-
史上最简单的Spring Security教程(十):AuthenticationFailureHandler高级用法
-
史上最简单的Spring Security教程(八):用户登出成功LogoutSuccessHandler高级用法
-
史上最简单的Spring Security教程(二):自定义登录页
-
史上最简单的Spring Security教程(五):成功登录SuccessHandler高级用法
-
史上最简单的Spring Security教程(四):成功登录页面
-
史上最简单的Spring Security教程(九):自定义用户登录失败页面
-
史上最简单的Spring Security教程(十一):url区分不同的登录失败场景