欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-02 16:15:25
...

 

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

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

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

还有,比如这样的。

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

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

其实,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);
    }
}

 

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

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

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

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

源码

github

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

gitee

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

 

 

 

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

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

 

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

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

 

 

 

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

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