Spring Boot 从 3.0.8 迁移到 3.0.9 后,SecurityFilterChain 无法实例化

Thi*_*arz 9 java spring-security spring-boot

在我的 Spring Boot 项目中,我对 SecurityFilterChain 进行了以下定义:

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  http

    // public routes
    .authorizeHttpRequests()
    .requestMatchers("/", "/favicon.ico", "/v3/api-docs*")
    .permitAll()
    .and()

    // enable security for the log-view
    .authorizeHttpRequests()
    .requestMatchers("/log")
    .hasAnyRole(ROLE_LOGVIEWER)
    .and()

    // enable security for the health check
    .authorizeHttpRequests()
    .requestMatchers("/manage/health")
    .hasAnyRole(ROLE_HEALTH)
    .and()

    // enable basic-auth and ROLE_USER for all other routes
    .authorizeHttpRequests()
    .anyRequest()
    .hasAnyRole(ROLE_USER)
    .and()
    .httpBasic();

  return http.build();
}
Run Code Online (Sandbox Code Playgroud)

它在多个模型测试中进行了测试,并在生产环境中按预期运行。

但是从 spring-boot 3.0.8 迁移到 3.0.9 后,出现以下错误:

Factory method 'filterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher).
Run Code Online (Sandbox Code Playgroud)

我尝试使用更具体的请求匹配器,但没有成功。

有什么提示给我吗?

use*_*589 9

我在 Spring Security 6.1.2 的非常基本配置中遇到了相同的异常。我用以下方法解决了它:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.
            authorizeHttpRequests(requests -> {
                    requests.requestMatchers(new AntPathRequestMatcher("/"), new AntPathRequestMatcher("/style.css")).permitAll();
                    requests.requestMatchers(new AntPathRequestMatcher("/secure/**")).hasAuthority("MyAuthority");
            }).
Run Code Online (Sandbox Code Playgroud)

我不确定这是否是正确的方法,但它似乎确实有效。在 Spring Security 6 中,AbstractRequestMatcherRegistry不再有.antMatchers()方法了。再说一次,我不太确定这是否是最好的方法,也不完全确定为什么我想要 ant 匹配器而不是 MVC 端点匹配器。


Thi*_*arz 1

user2959589 的回答告诉我正确的方法,谢谢!

http
    // public routes
    .authorizeHttpRequests()
    .requestMatchers(AntPathRequestMatcher.antMatcher("/"))
    .permitAll()
    .requestMatchers(AntPathRequestMatcher.antMatcher("/favicon.ico"))
    .permitAll()
    .requestMatchers(AntPathRequestMatcher.antMatcher("/v3/api-docs*"))
    .permitAll()
    .and()

    // enable security for the log-view
    .authorizeHttpRequests()
    .requestMatchers(AntPathRequestMatcher.antMatcher("/log"))
    .hasAnyRole(ROLE_LOGVIEWER)
    .and()

    // enable security for the health check
    .authorizeHttpRequests()
    .requestMatchers(AntPathRequestMatcher.antMatcher("/manage/health"))
    .hasAnyRole(ROLE_HEALTH)
    .and()

    // enable basic-auth and ROLE_USER for all other routes
    .authorizeHttpRequests()
    .anyRequest()
    .hasAnyRole(ROLE_USER)
    .and()
    .httpBasic();
Run Code Online (Sandbox Code Playgroud)