前不久Spring Boot 2.7.0 刚刚发布,Spring Security 也升级到了5.7.1 。升级后发现,原来一直在用的Spring Security配置方法,居然已经被弃用了。不禁感慨技术更新真快,用着用着就被弃用了!今天带大家体验下Spring Security的最新用法,看看是不是够优雅!
SpringBoot实战电商项目mall(50k+star)地址:github.com/macrozheng/…
基本使用
我们先对比下Spring Security提供的基本功能登录认证,来看看新版用法是不是更好。
升级版本
首先修改项目的pom.xml文件,把Spring Boot版本升级至2.7.0版本。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
旧用法
在Spring Boot 2.7.0 之前的版本中,我们需要写个配置类继承
WebSecurityConfigurerAdapter,然后重写Adapter中的三个方法进行配置;
/**
* SpringSecurity的配置
* Created by macro on 2018/4/26.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OldSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UmsAdminService adminService;
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//省略HttpSecurity的配置
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
如果你在SpringBoot 2.7.0版本中进行使用的话,你就会发现
WebSecurityConfigurerAdapter已经被弃用了,看样子Spring Security要坚决放弃这种用法了!
新用法
新用法非常简单,无需再继承
WebSecurityConfigurerAdapter,只需直接声明配置类,再配置一个生成SecurityFilterChainBean的方法,把原来的HttpSecurity配置移动到该方法中即可。
/**
* SpringSecurity 5.4.x以上新用法配置
* 为避免循环依赖,仅用于配置HttpSecurity
* Created by macro on 2022/5/19.
*/
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
//省略HttpSecurity的配置
return httpSecurity.build();
}
}
新用法感觉非常简洁干脆,避免了继承
WebSecurityConfigurerAdapter并重写方法的操作,强烈建议大家更新一波!
高级使用
升级 Spring Boot 2.7.0版本后,Spring Security对于配置方法有了大的更改,那么其他使用有没有影响呢?其实是没啥影响的,这里再聊聊如何使用Spring Security实现动态权限控制!