SpringBoot3版本下SpringSecurity的HttpSecurity配置
今天在写项目的时候,需要取消SpringSecurity对一些界面的屏蔽,需要配置HttpSecurity。
但是从SpringBoot2.7开始,WebSecurityConfigurerAdapter就被遗弃了,我们无法通过继承WebSecurityConfigurerAdapter类,然后重写configure()方法来进行配置,就像下面这样:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { ... } }
所以我们可以通过返回一个SecurityFilterChain类型的Bean方法来进行配置:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { ... @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests().antMatchers("/api/auth/**").permitAll() .antMatchers("/api/test/**").permitAll() .anyRequest().authenticated(); // http....; } }
但是,上面这种方法在我自己实现的时候,提示csrf()等很多方法都已经被遗弃。查阅相关资料后发现Springboot3中上述方式已经失效,我们需要用以下的表达方式:
@Configuration public class WebSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()) .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler)) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth.requestMatchers("/api/auth/**").permitAll() .requestMatchers("/api/test/**").permitAll() .anyRequest().authenticated()); // http....; return http.build(); }
成功,没有报错。希望能够帮到你.
下一篇:
python对excel删除指定行