Spring + H2DB-Web-Console:"This method cannot decide whether these patterns are Spring MVC patterns or not."

回答 3 浏览 4681 2023-09-01

我的最终目标是在我的应用程序中使用 h2db-web-console ,作为我本地开发环境的一部分。

我收到错误:

Caused by: java.lang.IllegalArgumentException: 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).

This is because there is more than one mappable servlet in your servlet context: {org.h2.server.web.JakartaWebServlet=[/my-h2-console/*], org.springframework.web.servlet.DispatcherServlet=[/]}.

For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path.

虽然这听起来很有描述性,但它让我发疯,因为看起来我使用 JakartaWebServlet=[/my-h2-console/*] 的路径并不重要,因为 DispatcherServlet=[ /] 只需匹配以“/” 开头的所有内容,也就是所有内容。

...please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher)...

好吧,Spring 3.x.x 已弃用这些 patchnotes 所以我尝试使用 RequestMatcher(这应该自动与“authorize”一起使用)。

Security-Config

    @Bean
    @Order(GENERAL_SECURITY_CONFIGURATION_ORDER)
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            ...
            }
            securityMatcher("/**")
            headers { frameOptions { disable() } }
            csrf { ignoringRequestMatchers("/my-h2-console/**") }

            authorizeRequests {
                authorize("/my-h2-console/**", permitAll)
                authorize("/ping", permitAll)
                authorize("/**", denyAll)
            }
        }
        return http.build()
    }

pom.xml

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope> <!-- Should be "test", revert later -->
        </dependency>

application.yml

spring:
  h2:
    console:
      enabled: true
      path: /my-h2-console
      settings:
        trace: false
        web-allow-others: false
  datasource:
    url: jdbc:h2:mem:testdb
    driverClassName: org.h2.Driver
    username: sa
    password:
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
  sql:
    init:
      mode: embedded
      schema-locations: classpath:sql/schema.testdb.local.sql

请记住,我对 Spring-boot 还很陌生,所以请多多包涵。如果您能提供与本主题相关的任何信息,我将不胜感激。 :)

我试过:

  • 如上所述更改 servlet 的路径/名称
  • 改变了我的 H2DB 的范围
  • 在我的Security-Config中尝试了不同的配置

=> 仅关闭/打开

spring:
  h2:
    console:
      enabled: true

似乎会带来任何改变。

Fuby1000 提问于2023-09-01
3 个回答
#1楼 已采纳
得票数 5

此配置帮助我解决了 H2 问题:

@Configuration
public class SecurityConfig {

    // My enpdoints start from /v1 so this pattern is ok for me
    private static final String API_URL_PATTERN = "/v1/**";

    @Bean
    public SecurityFilterChain getSecurityFilterChain(HttpSecurity http,
                                                      HandlerMappingIntrospector introspector) throws Exception {
        MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);

        http.csrf(csrfConfigurer ->
                csrfConfigurer.ignoringRequestMatchers(mvcMatcherBuilder.pattern(API_URL_PATTERN),
                        PathRequest.toH2Console()));

        http.headers(headersConfigurer ->
                headersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin));

        http.authorizeHttpRequests(auth ->
                auth
                        .requestMatchers(mvcMatcherBuilder.pattern(API_URL_PATTERN)).permitAll()
                        //This line is optional in .authenticated() case as .anyRequest().authenticated()
                        //would be applied for H2 path anyway
                        .requestMatchers(PathRequest.toH2Console()).authenticated()
                        .anyRequest().authenticated()
        );

        http.formLogin(Customizer.withDefaults());
        http.httpBasic(Customizer.withDefaults());

        return http.build();
    }
}

更多信息

更新了 H2 控制台的代码,以便在浏览器中正常工作。

也可以使用PathRequest.toH2Console()代替AntPathRequestMatcher.antMatcher("/h2-console/**")

Denis Korolev 提问于2023-09-10
Denis Korolev 修改于2023-11-11
是的,以下解决了我的问题,谢谢;authorize(PathRequest.toH2Console(), permitAll)Anıl Şenocak 2023-11-22
#2楼
得票数 0

试试 antMatcher 怎么样? 我不懂 kotlin 但希望有帮助

 authorizeRequests {
            authorize(antMatcher("/my-h2-console/**"), permitAll)
            //...
        }
biobebe 提问于2023-09-07
#3楼
得票数 0

@Denis Korolev 这解决了它,谢谢!

 @Bean
    fun securityFilterChainTestEnv(http: HttpSecurity): SecurityFilterChain {
        http {
                ...
            }

            headers { frameOptions { disable() } }
            csrf { ignoringRequestMatchers(AntPathRequestMatcher("/h2-console/**")) }

            http.authorizeHttpRequests { httpSecurity ->
                val mvcIntrospector = HandlerMappingIntrospector()
                httpSecurity
"/ping-test")).permitAll()
                    .requestMatchers(AntPathRequestMatcher("/h2-console/**")).permitAll()
                    .anyRequest().denyAll()
            }
        }
        return http.build()
    }
Fuby1000 提问于2023-09-11