版本为:SpringBoot3.1.2, Spring Security 6.1.2
博主学习三更博客项目的时候,在P35中遇到一个问题,在Spring Security6版本中,很多类被废弃,而且有些方法的名字和用法也已经更改,所以通过查询很多资料,将需要的更改总结如下:
1 更改SecurityConfig.java文件
@Configuration
//添加security过滤器
@EnableWebSecurity
public class SecurityConfig{
@Resource
UserDetailsServiceImpl userDetailsService;
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// 基于 token,不需要 csrf
// csrf表示跨域漏洞防御
// 可以使用Customizer.withDefaults():关闭
// 相当于csrf -> csrf.disable()
.csrf(csrf -> csrf.disable())
// 基于 token,不需要 session
.sessionManagement(withDefaults());
// 设置 处理认证失败、鉴权失败处理器
http.exceptionHandling(withDefaults());
http
// authorizeHttpRequests:针对http请求进行授权配置
// permitAll: 具有所有权限,也就是可以匿名访问
// authenticated: 认证【登录】
.authorizeHttpRequests(authorizeHttpRequests ->
authorizeHttpRequests
.requestMatchers("/login").anonymous()
// 其他地址的访问均需验证权限
.anyRequest().permitAll()
);
// 添加认证过滤器,过滤器在用户名密码认证过滤器之前
//.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class)
// 退出
//.logout(logout -> logout.disable());
//允许跨域
return http.cors(withDefaults()).build();
}
@Bean
// 密码加密,方便之后进行密码加密对比
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
return config.getAuthenticationManager();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
}
2 如果后续运行出现java.lang.ClassNotFoundException:javax.xml.bind.DatatypeConverter
需要在framework中的pom.xml中添加依赖
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
参考链接:
1 https://blog.csdn.net/weixin_43883917/article/details/124430507