我正在尝试将Spring Boot版本从2.6.9升级到3.0.5,Spring Security也将从5.7.5升级到6.0.2。
我正在使用自定义AuthenticationProvider,这在Spring启动后不被调用&Spring Security upgrade.
试题:
SecurityFilterChain (HttpSecurity http)方法变化,
-
在AuthenticationManager中注册自定义认证提供者。
List<AuthenticationProvider> authenticationProviders = new ArrayList<AuthenticationProvider>(1); authenticationProviders.add(customAuthenticationProvider()); AuthenticationManager authenticationManager = authenticationManager(authenticationProviders); http .csrf() .disable() .authorizeHttpRequests() .authenticationManager(authenticationManager) .logout().permitAll();
这不是调用自定义AuthenticationProvider。
-
还添加了身份验证提供者,但没有给出预期的结果
http.csrf() .disable() .authorizeHttpRequests() .authenticationManager(authenticationManager) .authenticationProvider(customAuthenticationProvider()) .logout().permitAll();
-
添加了AuthenticationResolver也不调用自定义身份验证提供程序。
http .csrf() .disable() .authorizeHttpRequests() .authenticationManager(authenticationManager) .oauth2ResourceServer() .authenticationManagerResolver(resolver(http)) .and() .authenticationProvider(customAuthenticationProvider()) .logout().permitAll(); public AuthenticationManager authManager(HttpSecurity http) throws Exception { AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); authenticationManagerBuilder.authenticationProvider(customAuthenticationProvider()); return authenticationManagerBuilder.build(); } AuthenticationManagerResolver<HttpServletRequest> resolver(HttpSecurity http) { return request -> { try { return authManager(http); } catch (Exception e) { e.printStackTrace(); } return null; }; }
我卡在这里,没有得到太多的线索来找出问题。如有任何帮助,不胜感激。
我浪费了一天的时间来调试问题,最终找到了解决问题的方法。有两个变化
-
虽然@EnableGlobalMethodSecurity(prePostEnabled = true)在Spring Boot 3.0.0中已弃用,但应该使用此注释。这样,secureEnabled为true并调用自定义AuthenticationProvider。我偶然发现@EnableMethodSecurity应该在Spring Boot 3.0.0中使用,而不是@EnableGlobalMethodSecurity。但是使用了@EnableMethodSecurity,而不是像预期的那样调用自定义AuthenticationProvider。
-
protected SecurityFilterChain filterChain(HttpSecurity http)方法有一个变化-
@Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors() .disable() .csrf() .disable() .authorizeHttpRequests() .requestMatchers("/domain/version/**").permitAll() .anyRequest() .authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .addFilterBefore(customFilter(), UsernamePasswordAuthenticationFilter.class) .logout().permitAll(); return http.build(); }
注意:custom AuthenticationProvider被注册为bean。
@Bean
public CustomAuthenticationProvider customAuthenticationProvider() {
return new CustomAuthenticationProvider ();
}