目录
废弃WebSecurityConfigurerAdapter
spring security中WebSecurityConfigurerAdapter弃用配置AuthenticationManagerBuilder
参考代码
部分pom.xml配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.4</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
SecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@Slf4j
public class SecurityConfig {
@Resource
private LoginFilter loginFilter;
@Resource
private UserMapper userMapper;
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("从数据库中拿 {} 用户信息", username);
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>().eq(User::getUsername, username);
User user = userMapper.selectOne(queryWrapper);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return new CustomDetailsUser(user);
}
};
}
@Bean
AuthenticationManager authenticationManager() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService());
daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder(10));
return new ProviderManager(daoAuthenticationProvider);
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// 关闭csrf
.csrf(csrf -> csrf.disable())
// 不通过session获取SecurityContext
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> {
// 允许登录接口匿名访问
auth.requestMatchers("/user/login").anonymous()
// 允许接口文档匿名访问
.requestMatchers("/v3/api-docs/**").anonymous()
.requestMatchers("/doc.html/**").anonymous()
.requestMatchers("/swagger-ui/**").anonymous()
.requestMatchers("/webjars/**").anonymous()
// 除上述之外的全部请求都需要鉴权认证
.anyRequest().authenticated();
});
// 增加过滤器
http.addFilterBefore(loginFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
标签:return,csrf,Spring,boot,requestMatchers,anonymous,解决方案,new,Security6
From: https://blog.csdn.net/qq_27516161/article/details/143566870