基本使用
我们先对比下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
,只需直接声明配置类,再配置一个生成SecurityFilterChain
Bean的方法,把原来的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实现动态权限控制!
基于方法的动态权限
首先来聊聊基于方法的动态权限控制,这种方式虽然实现简单,但却有一定的弊端。
- 在配置类上使用
@EnableGlobalMethodSecurity
来开启它;
/**
* SpringSecurity的配置
* Created by macro on 2018/4/26.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OldSecurityC