Spring Security专栏(关于安全配置)

514 阅读3分钟

这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战

写在前面

承接上文,我们最后留了个小尾巴,就是关于安全配置的东西,本节来讲讲。欢迎大家查看上一篇,这样更能有连贯性。

Spring Security专栏(自定义用户认证)

安全配置

今天我们要做的就是通过 Spring Security 提供的配置体系将前面介绍的所有内容串联起来,如下所示:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private AuthenticationProviderService authenticationProvider;
 
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
    @Bean
    public SCryptPasswordEncoder sCryptPasswordEncoder() {
        return new SCryptPasswordEncoder();
    }
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider);
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
            .defaultSuccessUrl("/healthrecord", true);
        http.authorizeRequests().anyRequest().authenticated();
    }
}

这里注入了已经构建完成的 AuthenticationProviderService,并初始化了两个密码加密器 BCryptPasswordEncoder 和 SCryptPasswordEncoder。最后,我们覆写了 WebSecurityConfigurerAdapter 配置适配器类中的 configure() 方法,并指定用户登录成功后将跳转到"/main"路径所指定的页面。

对应的,我们需要构建如下所示的 MainController 类来指定"/main"路径,并展示业务数据的获取过程,如下所示:

@Controller
public class HealthRecordController {
    @Autowired
    private HealthRecordService healthRecordService;
    
    @GetMapping("/healthrecord")
    public String main(Authentication a, Model model) {
        String userName = a.getName();
        model.addAttribute("username", userName);
        model.addAttribute("healthRecords", healthRecordService.getHealthRecordsByUsername(userName));
        return "health_record.html";
    }
}

我们通过 Authentication 对象获取了认证用户信息,同时通过 HealthRecordService 获取了健康档案信息。

请注意,这里所指定的 health_record.html 位于 resources/templates 目录下,该页面基于 thymeleaf 模板引擎构建,如下所示:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>健康档案</title>
    </head>
    <body>
        <h2 th:text="'登录用户:' + ${username}" />
        <p><a href="/logout">退出登录</a></p>
        <h2>个人健康档案:</h2>
        <table>
            <thead>
            <tr>
                <th> 健康指标名称 </th>
                <th> 健康指标值 </th>
            </tr>
            </thead>
            <tbody>
            <tr th:if="${healthRecords.empty}">
                <td colspan="2"> 无健康指标 </td>
            </tr>
            <tr th:each="healthRecord : ${healthRecords}">
                <td><span th:text="${healthRecord.name}"> 健康指标名称 </span></td>
                <td><span th:text="${healthRecord.value}"> 健康指标值 </span></td>
            </tr>
            </tbody>
        </table>
    </body>
</html>

这里我们从 Model 对象中获取了认证用户信息以及健康档案信息,并渲染在页面上。

案例

  • 1、现在,我们启动 Spring Boot 应用程序,并访问http://localhost:8080端点 因为访问系统的任何端点都需要认证,所以 Spring Security 会自动跳转到一个登录界面

  • 2、我们在登录界面分别输入用户名“yn”和密码“12345”,系统就会跳转到健康档案主页

  • 3 在最后出现的健康主页中,我们正确获取了登录用户的用户名,并展示了个人健康档案信息。这个结果也证实了自定义用户认证体系的正确性。大家可以自行敲一下代码 展示下

总结

通过上一篇和本次学习我们动手实践了如何利用 Spring Security 基础功能保护 Web 应用程序 。综合前面的核心知识点,我们又设计了一个简单而又完整的案例,并通过构建用户管理和认证流程讲解了实现自定义用户认证机制的过程。

今天我们就学习到这里。下一期我们主要学习下跨域和这个框架的扩展性。一起加油!

弦外之音

感谢你的阅读,如果你感觉学到了东西,您可以点赞,关注。也欢迎有问题我们下面评论交流

加油! 我们下期再见!

给大家分享几个我前面写的几篇骚操作

copy对象,这个操作有点骚!

干货!SpringBoot利用监听事件,实现异步操作