项目使用了SpringBoot3 ,因此 SpringSecurity也相应进行了升级 版本由5.4.5升级到了6.1.5 写法上发生了很大的变化,最显著的变化之一就是对 WebSecurityConfigurerAdapter 类的使用方式的改变。这个类在 Spring Security 中被广泛用于自定义安全配置。以下是主要的差异和写法上的变化:

  1. 废弃 WebSecurityConfigurerAdapter

    • 在 Spring Security 5.x 版本中,WebSecurityConfigurerAdapter 是实现安全配置的常用方法。用户通过继承这个类,并覆盖其方法来自定义安全配置。
    • 到了 Spring Security 6.x,WebSecurityConfigurerAdapter 被标记为过时(deprecated),意味着它可能在未来的版本中被移除。这一变化是为了推动使用更现代的配置方法,即使用组件式配置。
  2. 使用组件式配置:

    • 在 Spring Security 6.x 中,推荐使用组件式配置。这意味着你可以创建一个配置类,该类不再需要继承 WebSecurityConfigurerAdapter
    • 你可以直接定义一个或多个 SecurityFilterChain bean 来配置安全规则。这种方式更加灵活,并且与 Spring Framework 的整体风格更加一致。

示例代码变化:

  • 在 Spring Security 5.x 使用 WebSecurityConfigurerAdapter 的配置框架:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
  • 在 Spring Security 6.x 使用组件式配置变成了这个样子:
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
return http.build();
}
}

项目上具体的写法:

  • 在 Spring Security 5.4.5 使用 WebSecurityConfigurerAdapter 的配置:
@Configuration
@Component
@EnableWebSecurity
@AllArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Value("${auth.whitelist:/login}")
private final String[] URL_WHITELIST;
private final AuthenticationFailureHandler loginFailureHandler; private final UserLoginSuccessHandler loginSuccessHandler;
private final UserLogoutSuccessHandler logoutSuccessHandler;
private final UserDetailsService userDetailsService;
private final AccessDeniedHandler authAccessDeniedHandler;
private final AuthenticationEntryPoint loginAuthenticationEntryPoint; @Bean
BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
} @Bean
public UserAuthenticationProvider myAuthenticationProvider() {
UserAuthenticationProvider userAuthenticationProvider = new UserAuthenticationProvider(userDetailsService);
return userAuthenticationProvider;
} @Bean
JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
JwtAuthenticationFilter jwtAuthenticationFilter2 = new JwtAuthenticationFilter(authenticationManager());
return jwtAuthenticationFilter2;
} @Override
protected void configure(HttpSecurity http) throws Exception { http
.cors()
.and()
.csrf().disable()
.formLogin()
.loginProcessingUrl("/login")
.usernameParameter("userName")
.passwordParameter("password")
.successHandler(loginSuccessHandler)
.failureHandler(loginFailureHandler) .and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler) //禁用session
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) //配置拦截规则
.and()
.authorizeRequests()
.antMatchers(URL_WHITELIST).permitAll() .anyRequest().authenticated() //异常处理器
.and()
.exceptionHandling()
.authenticationEntryPoint(loginAuthenticationEntryPoint)
.accessDeniedHandler(authAccessDeniedHandler) .and()
.addFilterAfter(jwtAuthenticationFilter(), ExceptionTranslationFilter.class); }
}
  • 使用SpringSecurity6.1.5实现相同逻辑的配置变成了如下形式:
@Configuration
@Component
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration { @Value("${bxt.auth.whitelist:/login}")
private final String[] URL_WHITELIST; private final CustomerUserDetailsService customUserDetailsService;
private final CustomLoginSuccessHandler loginSuccessHandler;
private final CustomLoginFailureHandler loginFailureHandler;
private final AccessDeniedHandler authAccessDeniedHandler;
private final AuthenticationEntryPoint loginAuthenticationEntryPoint;
@Bean
BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
} @Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter(); // 实例化您的 JWT 过滤器
} @Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return new ProviderManager(new DaoAuthenticationProvider() {{
setUserDetailsService(customUserDetailsService);
setPasswordEncoder(bCryptPasswordEncoder());
}});
} @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeRequests(authz -> authz
.requestMatchers(URL_WHITELIST).permitAll() // 允许访问无需认证的路径
.anyRequest().authenticated()
)
.formLogin(form -> form.
loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(loginSuccessHandler)
.failureHandler(loginFailureHandler)
)
.logout(Customizer.withDefaults())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.userDetailsService(customUserDetailsService)
.exceptionHandling(exceptionHandle -> exceptionHandle
.authenticationEntryPoint(loginAuthenticationEntryPoint)
.accessDeniedHandler(authAccessDeniedHandler)
)
.addFilterAfter(jwtAuthenticationFilter(), ExceptionTranslationFilter.class)
.httpBasic(Customizer.withDefaults()); return http.build();
}
}

  总之,从 Spring Security 5.x 迁移到 6.x,主要的改变是从继承 WebSecurityConfigurerAdapter 转向定义 SecurityFilterChain bean 的方式来配置安全性。这种变化旨在使配置更加模块化和灵活,并更好地符合 Spring 框架的整体设计哲学。

比较Spring Security6.X 和 Spring Security 5.X的不同的更多相关文章

  1. Spring MVC 项目搭建 -6- spring security 使用自定义Filter实现验证扩展资源验证,使用数据库进行配置

    Spring MVC 项目搭建 -6- spring security使用自定义Filter实现验证扩展url验证,使用数据库进行配置 实现的主要流程 1.创建一个Filter 继承 Abstract ...

  2. Spring MVC 项目搭建 -5- spring security 使用数据库进行验证

    Spring MVC 项目搭建 -5- spring security 使用数据库进行验证 1.创建数据表格(这里使用的是mysql) CREATE TABLE security_role ( id ...

  3. Spring Boot中使用 Spring Security 构建权限系统

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...

  4. Spring Boot整合实战Spring Security JWT权限鉴权系统

    目前流行的前后端分离让Java程序员可以更加专注的做好后台业务逻辑的功能实现,提供如返回Json格式的数据接口就可以.像以前做项目的安全认证基于 session 的登录拦截,属于后端全栈式的开发的模式 ...

  5. 基于spring的安全管理框架-Spring Security

    什么是spring security? spring security是基于spring的安全框架.它提供全面的安全性解决方案,同时在Web请求级别和调用级别确认和授权.在Spring Framewo ...

  6. Spring Cloud 学习 (九) Spring Security, OAuth2

    Spring Security Spring Security 是 Spring Resource 社区的一个安全组件.在安全方面,有两个主要的领域,一是"认证",即你是谁:二是& ...

  7. Spring Boot中开启Spring Security

    Spring Boot中开启Spring Security Spring Security是一款基于Spring的安全框架,主要包含认证和授权两大安全模块,和另外一款流行的安全框架Apache Shi ...

  8. Spring实战1:Spring初探

    主要内容 Spring的使命--简化Java开发 Spring容器 Spring的整体架构 Spring的新发展 现在的Java程序员赶上了好时候.在将近20年的历史中,Java的发展历经沉浮.尽管有 ...

  9. Spring顶级项目以及Spring cloud组件

    作为java的屌丝,基本上跟上spring屌丝的步伐,也就跟上了主流技术. spring 顶级项目: Spring IO platform:用于系统部署,是可集成的,构建现代化应用的版本平台,具体来说 ...

  10. Spring Boot——开发新一代Spring应用

    Spring官方网站本身使用Spring框架开发,随着功能以及业务逻辑的日益复杂,应用伴随着大量的XML配置文件以及复杂的Bean依赖关系.随着Spring 3.0的发布,Spring IO团队逐渐开 ...

随机推荐

  1. 痞子衡嵌入式:恩智浦i.MX RT1xxx系列MCU启动那些事(10.A)- FlexSPI NAND启动时间(RT1170)

    大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是恩智浦i.MX RT1170 FlexSPI NAND启动时间. 本篇是 i.MXRT1170 启动时间评测第四弹,前三篇分别给大家评测 ...

  2. html表格基本标签

    1.<table>表签 <table>...</table>标签用于在html文档中后创建表格.它包含表名和表格本身内容的代码. 2.<tr>标签 &l ...

  3. pandas 显示所有的行和列

    import pandas as pd # 显示所有列,所有行 pd.set_option('display.max_columns', None) pd.set_option('display.ma ...

  4. MindSponge分子动力学模拟——安装与使用(2023.08)

    技术背景 昇思MindSpore是由华为主导的一个,面向全场景构建最佳昇腾匹配.支持多处理器架构的开放AI框架.MindSpore不仅仅是软件层面的工具,更重要的是可以协同华为自研的昇腾Ascend平 ...

  5. 【pytorch】目标检测:一文搞懂如何利用kaggle训练yolov5模型

    笔者的运行环境:python3.8+pytorch2.0.1+pycharm+kaggle.yolov5对python和pytorch版本是有要求的,python>=3.8,pytorch> ...

  6. k8s发布应用

    前言 首先以SpringBoot应用为例介绍一下k8s的发布步骤. 1.从代码仓库下载代码,比如GitLab: 2.接着是进行打包,比如使用Maven: 3.编写Dockerfile文件,把步骤2产生 ...

  7. 实在智能TARS-RPA-Agent,业界首发的产品级大模型Agent有何非凡之处?

    融合LLM的RPA进化到什么程度? AIGC如何借AI Agent落地? 像生成文本一样生成流程的ChatRPA,能够提升RPA新体验? 边探索边创建的ChatRPA,能否破解RPA与LLM融合难题? ...

  8. P3742题解

    思路 只需要让z串做到和y串一样,就得让y串每个字母(题意如此)均小于x串. 所以只要x串有一项小于y串,那么就输出-1,否则输出y串. 下面是核心代码: #include<bits/stdc+ ...

  9. 《SQL与数据库基础》03. SQL-DML

    目录 DML 数据插入 数据删除 数据更新 本文以 MySQL 为例 DML 数据插入 给指定字段添加数据: INSERT INTO 表(字段1, 字段2, ......, 字段n) VALUES(值 ...

  10. 重复的dna序列

    DNA序列 由一系列核苷酸组成,缩写为 'A', 'C', 'G' 和 'T'.. 例如,"ACGAATTCCG" 是一个 DNA序列 . 在研究 DNA 时,识别 DNA 中的重 ...