Spring中authorizeRequests已弃用,如何编写新版Spring Security配置?
Spring Security 6.x及以上版本中,旧的authorizeRequests方法已被移除,antMatchers也被requestMatchers替代。以下是适配新版本的正确配置写法,基于你提供的代码修改:
修改后的完整配置代码
@Configuration @EnableWebSecurity @EnableMethodSecurity(prePostEnabled = false, securedEnabled = true) public class SecurityConfig { private final PersonDetailsService personDetailsService; // Spring 4.3+ 支持单构造器自动注入,无需@Autowired public SecurityConfig(PersonDetailsService personDetailsService) { this.personDetailsService = personDetailsService; } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors() .and() .csrf().disable() // 替换弃用的authorizeRequests为authorizeHttpRequests .authorizeHttpRequests(authorize -> authorize // 替换antMatchers为requestMatchers,注意每个路径单独作为参数传递 .requestMatchers("/", "/login", "/signup", "/logout").permitAll() .requestMatchers("/api").hasRole("ADMIN") .requestMatchers("/user").hasRole("USER") .anyRequest().authenticated() ) // 用lambda风格配置logout,替代旧的链式.and()写法 .logout(logout -> logout .logoutUrl("/logout") .logoutSuccessUrl("/") ) // 用lambda风格配置formLogin,更清晰 .formLogin(form -> form .loginPage("/login") .loginProcessingUrl("/login") .defaultSuccessUrl("/user") .failureUrl("/login?error") ); return http.build(); } }
关键修改说明
- API替换:彻底移除
authorizeRequests和antMatchers,改用authorizeHttpRequests和requestMatchers,这是新版本的强制要求。 - 路径参数修正:原代码中
requestMatchers("/, /login, /signup, /logout")是错误写法,Spring会将整个字符串视为单个路径匹配。必须将每个路径单独作为参数传递,或使用字符串数组。 - 配置风格优化:新版本推荐使用lambda表达式配置
logout、formLogin等模块,避免过多.and()拼接,代码结构更清晰。 - 构造器注入简化:单构造器场景下可省略
@Autowired注解,Spring会自动完成注入。
内容的提问来源于stack exchange,提问作者GOLDProFA
相关产品推荐
相关产品推荐

