在Spring Security 5.7.0-M2中,WebSecurityConfigurerAdapter就已被标记为@Deprecated,从Spring Security 6.0.0开始更是直接移除弃用WebSecurityConfigurerAdapter,官方鼓励用户转向基于组件的安全配置。
而Spring Boot 3.0.0开始默认使用Spring Security 6.0.0,如果没有给spring-boot-starter-security配6.0.0以下版本就会报错。
对此官方建议使用SecurityFilterChain来替代WebSecurityConfigurerAdapter,下面示例中新配置的方式将使用Spring Security 5.2引入的lambda DSL(domain specific language,即领域专用语言)即lambda表达式,这里仅列出变动的配置。
下面是基于WebSecurityConfigurerAdapter的配置。
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/xx", "/xx/xx").permitAll()
.antMatchers("/xxx").hasAnyRole("ADMIN")
.anyRequest().authenticated()
.and()
.logout()
.logoutUrl("/logout").permitAll()
//清除身份认证信息
.clearAuthentication(true)
//使 Session失效
.invalidateHttpSession(true)
.deleteCookies("token")
.and()
.httpBasic(withDefaults());
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/ignore1", "/ignore2");
}
}
下面是基于SecurityFilterChain的新配置。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
public class SecurityConfiguration {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.requestMatchers("/xx", "/xx/xx").permitAll()
.requestMatchers("/xxx").hasAnyRole("ADMIN")
.anyRequest().authenticated()
)
.logout(logoutCustomizer -> logoutCustomizer
//注销登录请求url
.logoutUrl("/logout").permitAll()
//清除身份认证信息
.clearAuthentication(true)
//使 Session失效
.invalidateHttpSession(true)
.deleteCookies("token")
)
.httpBasic(withDefaults());
return http.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("/images/**", "/assets/**");
}
}
需要注意的是新版本配置中,“authorizeRequests”被标记为过时方法并且将在7.0版本移除,推荐使用“authorizeHttpRequests”;“antMatchers”换成“requestMatchers”;去掉了“and()”方法并且在7.0移除;等等。更多相关内容请访问:Spring Security without the WebSecurityConfigurerAdapter。
Spring Security目前最新版本是6.1.4,官方最新参考文档:Reference Doc、在线API文档:Api Doc。
展开阅读全文
上一篇: 解决Spring Boot 3+和Spring Security 6+框架下thymeleaf的sec:authorize等标签无效问题