Spring Boot:WebSecurityConfigurerAdapter已弃用,如何配置WebSecurityConfig?
问题解决方案
1. 移除弃用类与错误依赖
WebSecurityConfigurerAdapter在Spring Security 5.7.0+已被弃用,且WsConfigurerAdapter是Web Service配置类,和Web Security完全无关,直接去掉类的继承声明即可。
2. 替换弃用配置方法(使用SecurityFilterChain Bean)
Spring Security现在推荐通过定义SecurityFilterChain Bean替代原configure(HttpSecurity)方法,同时修正路径匹配和方法调用的错误:
修正后的完整代码
package com.securewebapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import com.securewebapp.auth.MySQLUserDetailsService; @Configuration @EnableWebSecurity @EnableMethodSecurity public class WebSecurityConfig { @Autowired private MySQLUserDetailsService mySQLUserDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .userDetailsService(mySQLUserDetailsService) .passwordEncoder(passwordEncoder()) .and() .build(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 配置请求权限 .authorizeHttpRequests(auth -> auth // 放行指定路径:主页、注册页、静态资源 .requestMatchers("/", "/home", "/register", "/css/**", "/js/**").permitAll() // 其他所有请求必须认证 .anyRequest().authenticated() ) // 配置表单登录 .formLogin(form -> form // 指定自定义登录页路径 .loginPage("/login") // 放行登录相关请求 .permitAll() ) // 配置注销 .logout(logout -> logout .permitAll() ); return http.build(); } }
3. 关键修正点说明
- 替换
antMatchers为requestMatchers:requestMatchers是Spring Security推荐的路径匹配方式,功能更全面;若需限制请求方法,需导入org.springframework.http.HttpMethod,写法为requestMatchers(HttpMethod.GET, "/path"),不要使用netty的HttpMethod类。 - 修正静态资源路径:原代码
/css/**.css写法错误,/css/**已能匹配/css下所有文件及子路径资源,无需额外加.css。 - 清理错误导入:删除
io.netty.handler.codec.http.HttpMethod和org.springframework.ws.config.annotation.WsConfigurerAdapter的无效导入。
4. 解决路由重定向问题
之前除/login外所有路由重定向的原因:
- 原
antMatchers参数错误(传入HttpMethod类而非具体枚举值),导致路径匹配失效,所有请求被判定为需认证; - 静态资源路径写法错误,导致静态资源也被拦截。
修正后指定路径会被正确放行,不会再强制重定向到登录页。
内容的提问来源于stack exchange,提问作者Thomas Kremer
相关产品推荐
相关产品推荐

