问题描述
最近使用Security的时候报了下面的错误:
配置如下:
@EnableWebSecurity
@Slf4j
public class SecurityConfig {@Resourceprivate CustUserService custUserService;@Beanpublic AuthenticationProvider authenticationProvider() {return new AuthenticationProvider() {@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String name = authentication.getName();String credentials = authentication.getCredentials().toString();UserDetails userDetails = custUserService.loadUserByUsername(name);if (credentials.equals(userDetails.getPassword())) {log.info("登录成功");return new UsernamePasswordAuthenticationToken(name, credentials, userDetails.getAuthorities());} else {log.info("登录失败");throw new BadCredentialsException("用户名密码错误");}}@Overridepublic boolean supports(Class<?> authentication) {return authentication.equals(UsernamePasswordAuthenticationToken.class);}};}@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authenticationProvider(authenticationProvider()).authorizeRequests((auth) -> {auth.anyRequest().authenticated();}).httpBasic(withDefaults());return http.build();}
}
我使用的是Springboot 2.3.3, 发现没有HttpSecurity注入Bean,SecurityFilterChain 是高版本的配置,所以不能在低版本使用。
解决方案一:可以参考这篇文章进行配置:
https://blog.csdn.net/bicheng4769/article/details/131205019
解决方案二:
升级Springboot 使用版本2.7.2,因为高版本给我们注入了这个Bean
此次踩坑告诉我,配置照网上粘贴如果遇到错误,可以检查一下是不是网上的版本和自己使用的版本有差异。