项目使用了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. rest-apiV2.0.0升级为simplest-api开源框架生态之simplest-jpa发布

    什么是 simplest simplest 追求存粹简单和极致. 旨在为项目快速开发提供一系列的基础能力,方便用户根据项目需求快速进行功能拓展 不在去关心一些繁琐.重复工作,而是把重点聚焦到业务. 前 ...

  2. 连续下雨天,.net开发者如何预防流感

    最近连续下了3天雨,天气变化大,很容易引发感冒咳嗽等疾病.对于.NET技术开发人员来说,如何保持身体健康,保证工作效率是一个很重要的问题. 首先,我们需要注意保持室内空气流通,避免长时间处于封闭的空间 ...

  3. [golang]使用gocron编写定时任务

    前言 linux自带的crontab默认情况下只能精确到分钟,没法执行秒级任务.当然,也不是不行,比如: * * * * * for i in $(seq 1 11);do echo hello &g ...

  4. Linux下发现一个高安全性的系统管理工具

    软件 AnySetup 主要功能 主要功能是对Linux操作系统下的基本配置进行管理.多种服务配置进行管理.安全配置进行管理等.如:操作系统的升级管理,软件包的安装.更新和卸载管理,软件仓库源的管理, ...

  5. 《SQL与数据库基础》02. SQL-DDL

    目录 DDL 库管理 表管理 本文以 MySQL 为例 DDL 库管理 查看有哪些数据库: SHOW DATABASES; 使用某个数据库: USE 数据库名; 查看当前使用的数据库: SELECT ...

  6. 全局多项式(趋势面)与IDW逆距离加权插值:MATLAB代码

      本文介绍基于MATLAB实现全局多项式插值法与逆距离加权法的空间插值的方法,并对不同插值方法结果加以对比分析. 目录 1 背景知识 2 实际操作部分 2.1 空间数据读取 2.2 异常数据剔除 2 ...

  7. UI自动化项目1说明 | 网页计算器自动化测试项目

    需求: 1.对网页计算器, 进行加法的测试操作. 通过读取数据文件中的数据来执行用例. 2.网址: http://cal.apple886.com/ 测试点: 1.加法:1+1=2 2+9!=10 . ...

  8. QA|如何获取元素属性值|网页计算器自动化测试实战

    一般来说 类似于<value>123</value>这样的元素,我们获取元素值是用.text获取,但有时这个值不是写在这里,而是作为标签的属性值写进去的,此时我们就需要获取属性 ...

  9. 【规范】SpringBoot接口返回结果及异常统一处理,这样封装才优雅

    前言 缘由 博友的需求就是我最大的动力 博友一说话,本狗笑哈哈.博友要我写啥,我就写啥. 特来一篇关于SpringBoot接口返回结果及异常统一处理,虽说封不封装都能用,但咱后端也得给前端小姐姐留个好 ...

  10. VScode+X11支持连接服务器时支持open3d、openCV、matplotlib等可视化

    背景 连接服务器以后,想用open3d可视化点云.matplotlib画点图,但是一直不能用,原因也很简单,就是没有配置GUI传输显示,那肯定是要配置X11相关的东西. 过程 服务器 确保服务器下载了 ...