基于Spring Boot 3.3.4,详细说明Spring Security 6.3.3的使用
- 摘要
- 本地开发环境说明
- SecurityFilterChain介绍
- application.yml
- Wen3SecurityProperties.java
- 修改DemoWen3Security
- 修改SecurityFilterChain
- IgnoredPathController.java
- IgnoredPathController2.java
- 启动工程
- 测试
- 测试免鉴权Path
- 接口响应
- 测试鉴权Path
- 接口响应
- 总结
摘要
【Spring Security】基于SpringBoot3.3.4版本①整合JWT的使用教程
在这篇文章中,详细演示了使用最新版Spring Boot,完成一个微服务开发,并使用Spring Security组件完成登录认证,同时整合了JWT,使用的RSA公私钥签名、验签。
接下来继续讲解下一个业务场景:一个真实场景的微服务,难免会有一些请求Path不需要任何鉴权,比如某些仅对内的API、允许匿名访问的资源等等。那么,如何在Spring Security体系中,把这些免鉴权的Path绕过认证呢?并且可以灵活的配置呢?
接下来让我就带着你一起解决这个业务场景中的问题吧!
本地开发环境说明
开发用到的主要框架、工具版本如下
| 开发依赖 | 版本 |
|---|---|
| Spring Boot | 3.3.4 |
| Spring Security | 6.3.3 |
| JDK | 21 |
| IntelliJ IDEA | 2024.2.3 |
【Spring Security】基于SpringBoot3.3.4版本①整合JWT的使用教程 建议大家先阅读这篇文章,本文是对这篇文章的进一步扩展。
SecurityFilterChain介绍
我们在构建SecurityFilterChain的时候,可以通过authorizeHttpRequestsCustomizer.requestMatchers(HttpMethod.POST, "/login/common").permitAll()这种方式告诉Spring Security,对于/login/common这个path不需要鉴权,代码如下
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {Wen3SecurityProperties wen3SecurityProperties = wen3SecurityProperties();http.authorizeHttpRequests(authorizeHttpRequestsCustomizer -> {authorizeHttpRequestsCustomizer.requestMatchers(HttpMethod.POST, "/login/common").permitAll().requestMatchers(HttpMethod.GET, "/login/verify").permitAll().requestMatchers(new AntPathRequestMatcher("/**/test")).permitAll().anyRequest().authenticated();});// token校验过滤器http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);// 禁用表单提交 取消默认的登录页面http.formLogin(AbstractHttpConfigurer::disable);// 禁用注销 取消默认的登出页面http.logout(AbstractHttpConfigurer::disable)